Recognize classes and objects

Classes and objects

Objectives of this chapter

  • Be able to understand object-oriented ideas
  • Be able to clarify the relationship between classes and objects
  • Be able to master the definition format of classes
  • Be able to master the format of creating objects and access members in classes
  • Be able to complete mobile phone exercises
  • Be able to understand the memory diagram of objects
  • Be able to tell the difference between member variables and local variables
  • Be able to understand the meaning of private keyword
  • Be able to say the problems that this keyword can solve
  • Be able to understand the meaning of construction method
  • Be able to define a standard class with the idea of encapsulation

1. Object oriented idea

1.1 general

Alan Kay: The best way to predict the future is to invent it!

OOP: Object-Oriented Programming

Java language is an object-oriented programming language, and object-oriented idea is a programming idea. Under the guidance of object-oriented idea, we use java language to design and develop computer programs. The object here generally refers to all things in reality, and each thing has its own attributes and behavior.

The object-oriented idea is the design idea of abstracting the attribute characteristics and behavior characteristics of things with reference to real things in the process of computer programming and describing them as computer events. It is different from the process oriented idea, which emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step.

1.2 examples

Steps to put the elephant into the refrigerator:

  • Facing the process: open the refrigerator door – > put the elephant in the refrigerator – > close the refrigerator door
  • Object oriented: create elephant – > create refrigerator – > call the method of loading things in the refrigerator to load the elephant into the refrigerator

difference:

  • Process oriented: emphasize steps.
  • Object oriented: emphasize objects. The objects here are elephants and refrigerators.

characteristic:

  • Object oriented thinking is an idea more in line with our thinking habits. It can simplify complex things and turn us from executor to commander. Object oriented language contains three basic features, namely encapsulation, inheritance and polymorphism.

1.3 classes and objects

Looking around, you will find many objects, such as tables, chairs, classmates, teachers and so on. Desks and chairs belong to office supplies. Teachers and students are human beings. So what is a class? What is an object?

What is a class

Class: a collection of related properties and behaviors. It can be regarded as the template of a kind of things, and the attribute characteristics and behavior characteristics of things are used to describe this kind of things.

In reality, describe a class of things:

  • Attribute: is the state information of the thing.
  • Behavior: is what the thing can do.

Example: kitten. Attributes: name, weight, age, color. Behavior: walk, run and shout.

What is an object

Object: it is the concrete embodiment of a kind of things. An object is an instance of a class (an object is not looking for a girlfriend), and it must have the properties and behavior of such things.

In reality, an example of a kind of thing: a kitten.

Example: a kitten.

Attributes: tom, 5kg, 2 years, yellow. Behavior: sneaking around the wall, jumping and running, meowing.

Relationship between classes and objects

  • Class is the description of a class of things, which is abstract.
  • An object is an instance of a class of things and is concrete.
  • Class is the template of object, and object is the entity of class.

1.4 definition of class

Comparison of things and classes

A kind of things in the real world: attribute: the state information of things. Behavior: what things can do.

The same is true for describing things with class in Java: member variable: attribute of corresponding things; member method: definition format of behavior class of corresponding things

Class definition format

[Access modifier ] class Class name {
    //Member variable
    //Member method
}

Define class: defines the members of a class, including member variables and member methods.

  • Member variables: almost the same as previously defined variables. It's just that the location has changed. In a class, outside a method.
  • Member methods: functions, procedures
    • It is used to encapsulate a specific business logic function
    • Methods should be as independent as possible. A method only does one thing
    • Once a method is defined, it can be called repeatedly
    • Benefits: reduce code duplication, facilitate program maintenance, and facilitate team collaborative development

Definition of method:

[Access modifier ] Return value type method name(parameter list){
	//Method body
}
  • Modifier: public private protected
  • Return value type: indicates the data type of the result of the method operation. After the method is executed, the result is returned to the caller. If there is no return value, it is modified with void
  • Parameter list: unknown data of the method during operation, which is passed when the caller calls the method
  • Return: bring the result of the method execution to the caller. After the method is executed to return, the whole method ends. If there is no return value, you do not need to use return
    • return value: ends the execution of the method and returns the result to the caller
    • return: ends the execution of the method

Method call:

  • No return value: method name (passed from parameter to parameter);

  • With return value: data type variable = method name (with parameter passed to parameter);

    • Later, you need to use some data in the method -- there is a return value
    • Some data in the method is no longer needed later - no return value

Using class diagrams to describe classes

1.5 use of objects

Create object:

Class name object name = new Class name();

Use objects to access members in a class:

Object name.Member variable;
Object name.Member method();

Default values for member variables

data typeDefault value
Basic typeInteger (byte, short, int, long)0
float, double0.0
Character (char)'\u0000'
booleanfalse
reference typeArray, class, interfacenull

1.6 object memory distribution diagram

Memory diagram of an object, calling member variables and member methods:

Customize the School class. The code is as follows:

public class School {
	String schoolName;		//Center Name
	int classNumber;		//Number of classrooms
	int labNumber;			//Number of machine rooms
	
	//How to define the display center
	public void showCenter(){
		System.out.println(schoolName + "Training trainees\n" + "equipment:" 
			+ classNumber + "teach" + labNumber + "machine");
	}
}

Create and use objects with the following code:

public class InitialSchool {
	public static void main(String[] args) {
		School center = new School();
		System.out.println("***Before initializing member variables***");
		center.showCenter();
		center.schoolName = "Beijing Center";		//Assign a value to the schoolName property
		center.classNumber = 10;			//Assign a value to the classNumber property
		center.labNumber = 10;				//Assign a value to the labNumber attribute
		System.out.println("\n***After initializing member variables***");
		center.showCenter();
	}
}

The memory distribution is shown in the figure:

1.7 differences between member variables and local variables

Variables are given different names according to different definition positions. As shown in the figure below:

  • Different positions in the class focus
    • Member variable: in class, outside method
    • Local variable: in method or on method declaration (formal parameter)
  • The scope of action is different and the focus is different
    • Member variables: in classes
    • Local variables: in method
  • Different focus of initialization value
    • Member variables: have default values
    • Local variable: no default value. You must first define, assign, and then use
  • Different locations in memory
    • Member variables: heap memory
    • Local variables: stack memory
  • Different understanding of life cycle
    • Member variable: exists with the creation of the object and disappears with the disappearance of the object
    • Local variable: exists with the method call and disappears with the method call

2. Packaging

2.1 package overview

summary

Object oriented programming language is a simulation of the objective world. In the objective world, member variables are hidden in the object, and the outside world can't operate and modify them directly.

Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being freely accessed by other classes. To access the data of this class, you must use the specified method. Proper encapsulation can make the code easier to understand and maintain, and also strengthen the security of the code.

principle

Property privatization, behavior disclosure

2.2 steps of packaging

  1. Use the private keyword to decorate member variables.
  2. For the member variables to be accessed, provide a corresponding pair of getXxx methods and setXxx methods.

2.3 realize packaging

  1. Use private to modify the member variable. The code is as follows:

    public class Student {
        private String name;
        private int age;
    }
    
  2. Provide getXxx method / setXxx method to access member variables. The code is as follows:

    public class Student {
        private String name;
        private int age;
        public void setName(String name) {
        	this.name = name;
        }
        public String getName() {
        	return name;
        }
        public void setAge(int age) {
        	this.age = age;
        }
        public int getAge() {
        	return age;
        }
    }
    

remarks:

Meaning of private

  1. private is a permission modifier that represents the minimum permission.
  2. You can modify member variables and member methods.
  3. Member variables and member methods modified by private can only be accessed in this class.

The meaning of this

this represents the reference (address value) of the current object of the class, that is, the reference of the object itself.

Remember: this in the method represents the object to which the method is called. That is, this represents who is calling.

2.4 construction method

When an object is created, the constructor is used to initialize the object and assign the initial value to the member variable of the object.

Tip: whether you customize the construction method or not, all classes have construction methods, because Java automatically provides a parameterless construction method. Once you define the construction method, the default parameterless construction method automatically provided by Java will become invalid.

Definition format of construction method

Modifier constructor name(parameter list){
	// Method body
}

The method name is the same as the class name of the constructor. It doesn't have a return value, so it doesn't need a return value type, or even void. After using the construction method, the code is as follows:

public class Student {
    private String name;
    private int age;
    // Nonparametric construction method
    public Student() {}
    // Parametric construction method
    public Student(String name,int age) {
    	this.name = name;
    	this.age = age;
    }
}

matters needing attention

  1. If you do not provide a construction method, the system will give a parameterless construction method.
  2. If you provide a constructor, the system will no longer provide a parameterless constructor.
  3. Construction methods can be overloaded, either with or without parameters.

2.5 method overload

Method overload:

It means that more than one method with the same name is allowed in the same class, as long as their parameter lists are different, regardless of modifiers and return value types.

  • Parameter list: different numbers, data types and orders.
  • Overloaded method call: the JVM calls different methods through the parameter list of the method.

2.6 static modifier

1. Basic concepts of static keyword

We can summarize it in one sentence: it is convenient to call without creating an object.

In other words, those modified by the static keyword do not need to create an object to call, but can be accessed directly according to the class name. This concept is described below according to the five basic uses of the static keyword.

2. static keyword modification class

Static in Java is generally used to modify member variables or functions. However, there is a special use of static to modify internal classes. Ordinary classes are not allowed to be declared static, and only internal classes can be declared. Demonstration examples are as follows:

public class StaticTest {
	public static class InnerClass{
		InnerClass(){
			System.out.println("======Static inner class======");
		}
	}
	public static void main(String[] args) {
		//Access the static inner class InnerClass directly through the StaticTest class name
		//Static inner classes can be used just like normal classes
		InnerClass inner = new StaticTest.InnerClass();
        //Note: if InterClass is not modified with static, only one external class instance can be new.
        // Then create an internal class through an external instance
        //StaticTest st =  new StaticTest();
		//InnerClass inner = st.new InnerClass();
	}

}
/* The output is:
 * ======Static inner class======
 */

If you do not modify InterClass with static, you can only new an external class instance. Then create an internal class through an external instance.

If static is not used to modify InterClass, the code for creating InnerClass object is as follows:

StaticTest st =  new StaticTest();
InnerClass inner = st.new InnerClass();

3. Modification method of static keyword

When decorating a method, it is actually the same as a class. It can be called directly through the class name. The demonstration example is as follows:

public class StaticMethod {
	public static void test() {
		System.out.println("======Static method======");
	}
	public static void main(String[] args) {
		//Method 1: call directly through the class name
		StaticMethod.test();
		//Method 2: call through object
		new StaticMethod().test();
	}
}

4. static keyword modifies member variables

The member variable modified by static is called static variable, also called class variable, which indicates that this variable belongs to this class rather than an object. The member variable not modified by static is called instance variable, which indicates that this variable belongs to a specific object

We can also use the above method to call variables:

public class StaticVar {
	private static String name = "====Static variable====";
	public static void main(String[] args) {
		//Method 1: call directly through the class name
		String name = StaticVar.name;
		//Method 2: call through object
		name = new StaticVar().name;
	}
}

5. static keyword modifies the code block

The code block modified by static is called static code block, which is executed when the class is first loaded. Use the code to verify the following:

public class StaticCode {
	static {
		System.out.println("=======Static code block======");
	}

	public static void main(String[] args) {
	}
}
/* Output:
 * =======Static code block======
 */

In the case of inheritance, the initialization order of parent-child class static members, ordinary members, code blocks and constructors is as follows:

Parent static variable – > parent static code block – > child static variable – > child static code block – >

Parent common variable – > parent common code block – > parent constructor – > subclass common variable – > subclass common code block – > subclass constructor

Use the code to verify the following:

The parent class code is as follows:

public class Father {
	static {
		System.out.println("====Parent static code block====");
	}
	{
		System.out.println("====Parent code block====");
	}
	
	public Father() {
		System.out.println("====Parent class constructor====");
	}
	
}

Subclass codes are as follows:

public class Son extends Father {
	static {
		System.out.println("====Subclass static code block====");
	}
	{
		System.out.println("====Subclass code block====");
	}
	
	public Son() {
		System.out.println("====Subclass constructor====");
	}
	
	public static void main(String[] args) {
		Son son = new Son();
	}
	
}
/* Output:
 * ====Parent static code block====
 * ====Subclass static code block====
 * ====Parent code block====
 * ====Parent class constructor====
 * ====Subclass code block====
 * ====Subclass constructor====
 */

6. static keyword static import

The syntax of static import is:

  • import static package name. Class name. Static member variable;
  • import static package name. Class name. Static member method;

Note that you are importing Member Variables and method names.

The demonstration code is as follows:

//Static import static member variables
import static java.lang.System.out;
//Static import static member method
import static java.lang.System.currentTimeMillis;
public class StaticImport {
	public static void main(String[] args) {
		out.println("Test static import static member variables");
		long time = currentTimeMillis();
		out.println(time);
	}
}

2.7 in depth analysis of static keyword

We just described the basic usage scenario of the static keyword above. The following mainly analyzes the deep principle of the static keyword.

To understand why static has the above features, we need to start with jvm memory. We first give a memory structure diagram of java, and then describe where the static modified variables are stored through an example.

The memory diagram is as follows:

From the above figure, we can find that static variables are stored in the method area and shared by all threads. Let's talk about the java heap. The java heap stores instance variables we create.

Stacking area:

  1. All stored objects are objects, and each object contains the information of a corresponding class. (the purpose of class is to get operation instructions)

  2. The jvm has only one heap shared by all threads. The heap does not store basic types and object references, but only the object itself

Stack area:

  1. Each thread contains a stack area. The stack only stores the references of basic data type objects and custom objects (not objects), and the objects are stored in the heap area

  2. The data (primitive types and object references) in each stack is private and cannot be accessed by other stacks.

  3. The stack is divided into three parts: basic type variable area, execution environment context and operation instruction area (storing operation instructions)

Method area:

  1. Also known as static area, like heap, it is shared by all threads. The method area contains all class and static variables.

  2. The method area contains elements that are always unique in the whole program, such as class and static variables.

The following is a case to illustrate why the static keyword has such a feature from the perspective of memory.

First, we define a class:

public class Emp {
	static String firstName;
	String lastName;
	public void showName() {
		System.out.println(firstName+lastName);
	}
	public static void viewName() {
		System.out.println(firstName);
	}
	
	public static void main(String[] args) {
		Emp e1 = new Emp();
		Emp.firstName = "Zhang";
		e1.lastName = "three";
		e1.showName();
		Emp.viewName();
		
		Emp e2 = new Emp();
		Emp.firstName = "Lee";
		e2.lastName = "four";
		e2.showName();
		Emp.viewName();
		
	}
	
}

Next, let's take a look from the perspective of memory

As can be seen from the above, our method is called from the method area, but the heap memory is different. The member variable lastName in the heap memory is generated with the generation of objects. Disappear as the object disappears. Static variables are shared by all threads, so they will not disappear. This can also explain the real reason for the static keyword above.

2.8 static summary:

The following is a summary of the static keyword:

(1) Features:

1. Static is a modifier used to decorate members. (member variable, member function) the member variable modified by static is called static variable or class variable.

2. Members decorated with static are shared by all objects.

3. static takes precedence over the object because its members already exist as the class loads.

4. The static modified member has an additional calling method, which can be directly called by the class name (class name. Static member).

5. The data modified by static is shared data, and the data stored in the object is unique data.

(2) Differences between member variables and static variables:

1. Different life cycles:

  • Member variables exist with the creation of objects and are released with the recycling of objects.

  • Static variables exist with the loading of the class and disappear with the disappearance of the class.

2. Different calling methods:

  • Member variables can only be called by objects.

  • Static variables can be called by object or class name. (it is recommended to call with class name)

3. Different aliases:

  • Member variables are also called instance variables.

  • Static variables are called class variables.

4. Different data storage locations:

  • Member variable data is stored in objects in heap memory, so it is also called object specific data.

  • Static variable data is stored in the static area of the method area (shared data area), so it is also called object shared data.

(3) Precautions for static use:

1. Static methods can only access static members. (non static can access both static and non static)

2. this or super keywords cannot be used in static methods.

3. The main function is static

Tags: Java

Posted on Mon, 11 Oct 2021 21:13:00 -0400 by dm404