JAVA Basics - encapsulated fields, inheritance and polymorphism

preface

Three basic characteristics of object-oriented: encapsulation, inheritance and polymorphism. For more detailed concepts, see the blogger's article Three characteristics and five basic principles

Tip: the following is the main content of this article. The following cases can be used for reference

1, Encapsulate field

1. Concept:
Encapsulating fields is an operation of refactoring code, which accesses fields through a pair of access methods. Access methods are also called read / write methods or getter and setter methods. Usually, when encapsulating a field, the access modifier of the field is changed to private, so the field cannot be referenced directly from outside the class. If other classes want to reference this field, they must use access methods.
Readable property get(); Writable property set()
2. Function:
(1) Using the encapsulate fields refactoring operation, you can quickly create attributes from existing fields and then seamlessly update code with references to new attributes.
(2) When the field is public, other objects can directly access the field and modify it without being detected by the object owning the field. By encapsulating the field with attributes, you can prohibit direct access to the field.
(3) To create a new attribute, the encapsulate field operation changes the access modifier for the field to be encapsulated as private, and then generates get and set accessors for the field.
3. Quick code generation method:
Right click source - > generate getters and setters
4. Code example:
Although fast generation is more convenient, if beginners want to better understand this method, it is recommended to try to write it several times. The following is an example to illustrate how to encapsulate a field:

public class E01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Teacher t = new Teacher(1001);//Call constructor
		
		int y = t.getTid();
		System.out.println(y);
		
		t.setTname("Zhang San");
		t.teach();
		
		t.setTage(18);
		t.teach();
		int a = t.getTage();
		System.out.println(a);
	}

}
//Write entity class
class Teacher {
	/*Some things cannot be modified, so when writing code, pay attention to writing the attribute field as private,
	Open by method*/
	//Attribute (field) number, name, age, course|
	private int tid;//It is assumed that it is readable but not writable
	private String tname;// Writable unreadable
	private int age;//Readable and writable
    
	//Private methods can't assign values, so we need constructors. Generally, we write one with theout and with the parameters, otherwise an error will occur
	public Teacher() {
		
	}
	public Teacher(int tid) {
		this.tid=tid;
	}
	//1. Readable but not writable
	public int getTid() {
		return this.tid;
	}
	
	//2. Writable and unreadable
	public void setTname(String tname)// Writable
	{
		this.tname = tname;
	}

	//3. Writable and readable
	public void setTage(int age) {
		this.age = age;
	}
	public int getTage() {
		return this.age;
	}
	

	// Behavior Teaching
	public void teach() {
		System.out.println(this.tname + "Teachers need to teach!");
	}

}

Simply draw a picture for everyone to understand

2, Inherit

1. Concept: inheritance is that a subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class. For example, animals (parent), dogs (child).
2. Function:
Improve reusability, reduce the amount of code, and improve the relationship between is
3. Features:
(1) The inherited keyword is extends.
(2) Java only supports single inheritance, not multiple inheritance, but multiple inheritance.
(3) Inherits all member properties of the parent class (private also inherits), but the constructor is not inherited.
4. Example code:

public class E02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Animal dog= new Dog();//Upward transformation
		dog.speak();
	}

}
//Parent class
class Animal{
	public String type;//
    
	public void speak() {
		System.out.println("I don't know what language");
	}
}
//Subclass
class Dog extends Animal{//JAVA only supports single inheritance, but supports multiple inheritance.
	//The subclass inherits the members of the parent class, and we have to transform the inherited members (mainly member methods)
	//Transform the member method inherited from the parent class and override the method.
	//Quickly generate the code, enter sp, and then alt+/
	@Override
	public void speak() {
		// TODO Auto-generated method stub
		System.out.println("Dogs bark");
	}
}

5. Recommended article: if you want to have a deep understanding of inheritance, you can take a look at this article article , it's really well written. There are pictures that can facilitate you to better understand the concept of inheritance.

3, Polymorphism

1. Concept: polymorphism is the ability of the same behavior to have multiple different forms or forms.
2. Features:
Polymorphism can be divided into dynamic polymorphism and static polymorphism:
(1) Dynamic polymorphism (runtime polymorphism): the same operation, acting on different instances, produces different results. In order to realize dynamic polymorphism, it also needs to transform upward. The variables corresponding to their instances are the same data type (type of parent class). For example:

	Vehicle1 v = new Car();
	v.move();
	
	v = new Bike();
	v.move();	(Change form---Upward transformation).

(2) Static polymorphism (compile time polymorphism): overloading of methods
3. Code example:
The last question can also be written in the public class

4. Recommended articles: polymorphic

4, Relevant necessary knowledge points

(1) A final keyword
1. Usage scenario
(1) There are some methods in the parent class that prohibit children from transforming it (overriding is not allowed). At this time, we modify the method with the final keyword.
(2) Some classes cannot have subclasses. We can modify this class with the final keyword. This class is the final class.
2. Function: (interview question)
(1) When decorating a class, the class cannot be inherited (the final class).
(2) When decorating a method, the method cannot be overridden (final method)
(3) When modifying a member variable, once the member variable is initialized, it cannot be modified.
Where can I modify variables modified by final?
A. Constructor
B. Instance block
C. Static block
D. This variable can be assigned directly when declared
(4) When modifying a local variable, once the local variable is initialized, it cannot be modified.
(5) When modifying parameters, the parameters cannot be changed.
3. Code example:

(2) A this keyword
this keyword: refers to the reference of the object of the current class.
effect:
(1) A member that references the current object.
(2) This (parameter list...) makes calls between constructors

(3) A super keyword
super keyword: refers to the reference of the substitute parent class, which corresponds to this in usage

effect:
(1) Using super Member to access members of the parent class. An example is as follows:

//Parent class
class Animal{
	public String type;//
    
	public void speak() {
		System.out.println("I don't know what language");
	}
}
//Subclass
class Dog extends Animal{
	@Override//annotation
	public void speak() {
		super.speak();
		System.out.println("Dogs bark");
	}
}

The operation results are shown in the figure:

(2) Super (parameter), call the constructor of the parent class

public class E02 {

	public static void main(String[] args) {
		//Animal dog= new Dog();// Upward transformation
		//dog.speak();
		Dog d= new Dog();//Top down
	}

}
//Parent class
class Animal{
   public String type;//
   public Animal() {
	   System.out.println("animal");
    }
}
//Subclass
class Dog extends Animal{
	public Dog() {
		//super() is hidden;
		System.out.println("dog");
	}
	
}


(4) A Access modifier
1.public: it can be accessed anywhere
2.private: this class can access
3.protected: inheritance relationship (can be different packages) or the same package
4. Package (default): the same package
(5) A static keyword
Let me give you an example to understand

public class E03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student student = new Student();
		student=new Student();
		student=new Student();
	}
}
class Student{
	//The student number is exactly the student counter
	public static int sid =0;//Member instance variable
	public String sname;
	
	public Student() {
		sid++;
		System.out.println("The first"+sid+"Students");
	}
}


1. Members with static keywords are called static members. Static members include static member variables and static member methods. Static members are loaded when the class is loaded. Static instances are loaded successively. There are classes before objects.
2. Static members are shared by all objects (shared by types). Therefore, when accessing, the class name member name
3. If the static keyword is not added, it is called an instance member. It belongs to an object and the member is generated when the object is generated.
4. Common scenarios of static members:
(1) When writing tool classes, in order to simplify code and save memory.
(2) When all members of your tool class are static, you need to prevent them from generating objects. How to prevent them? Write a private constructor. For example: Math class

5, Summary of interview questions

1. Please elaborate on inheritance?
2. Function of super keyword?
3. How many access modifiers are there? What does everyone mean?
4. How many places can final keyword be modified?

Keywords: Java Back-end

Added by omarh2005 on Sun, 16 Jan 2022 02:44:24 +0200