Quickly understand the three basic characteristics of object-oriented (encapsulation, inheritance and polymorphism) from [example]!

Three basic characteristics of Java object-oriented (encapsulation, inheritance and polymorphism)

The encapsulation of class is equivalent to a black box. You can't see anything in the black box.
Inheritance is an important feature of classes. Relatively complex and advanced classes can be inherited from a simple class, which can greatly reduce the workload of programming.
Polymorphism can dynamically call objects, which is the relative independence between objects.

1.Java access modifier

Before learning the three major features of java object-oriented, let's learn about Java access modifier.

There are four kinds of access rights in Java: public, private, protected and default. But the default permission has no access modifier. The default access permission is package access permission, that is, classes, properties and methods defined without any modifiers can be accessed in a package. The details are as follows:

publicprivateprotectdefault
classCan be accessed by all classesOnly internal classes are allowed to be private and can only be accessed in the current classOnly internal classes can be set with protection permission, and classes and their subclasses in the same package can be accessedCan be accessed by classes in the current package
attributeCan be accessed by all classesCan only be accessed by the current classCan be accessed by classes in the same package and subclasses of the current classCan be accessed by classes in the same package
methodCan be accessed by all classesCan only be accessed by the current classCan be accessed by classes in the same package and subclasses of the current classCan be accessed by classes in the same package

2. Packaging

We use examples to explain encapsulation more vividly.

2.1 examples of packaging problems

[example 1-A cat of uncontrollable quality 🐱]

public class TestCat {
	public static void main(String[] args) {
		MyCat aCat=new MyCat();
		aCat.weight=-10.0f;//Set the attribute value of MyCat
		float temp=aCat.weight;//Gets the property value of MyCatde
		System.out.println("The weight of a cat is"+temp);
		
	}

}
class MyCat{
	public float weight;//Open the attributes of MyCat to the outside world through the public modifier
	MyCat(){}
}

The calculation result is as above. Let's analyze the example code:
​ 1. First, let's analyze the MyCat class. In line 15, open the attribute (weight) of MyCat to the outside world through the public modifier, which means that the outside world can access (read or write) this attribute through "object name. Attribute name". Line 16 declares a parameterless construction method, which has no obvious meaning in this example.

​ 2. Line 05, define an object aCat. Line 07 obtains the value of this object through the point operator. Line 08 outputs the attribute value of this object. We need to focus on line 06, which sets the value (- 10.0) f of this object through the "point operator".

​ 3. In a general sense, "- 10.0f" is an ordinary legal single precision floating-point number, so it has no problem assigning weight in pure syntax. But for a real object (CAT), this is totally unacceptable. How can a cat's weight be negative? This is obviously "an unqualified cat", but because the attribute of weight is open to the outside world, "cat's weight value" cannot be "independent" because its value can be affected by any external behavior.

2.2 examples of packaging problems

[example 2-A difficult cat to access 🐱]

public class TestCat2 {
	public static void main(String[] args) {
		MyCat aCat=new MyCat();
		aCat.weight=-10.0f;//Set the attribute value of MyCat
		float temp=aCat.weight;//Gets the property value of MyCatde
		System.out.println("The weight of a cat is"+temp);
		
	}

}
class MyCat{
	private float weight;//Open the attributes of MyCat to the outside world through the private modifier
	MyCat(){}
}

Unlike example 1, when declaring the attribute weight in the MyCat class, the private modifier is used. This makes the following code compilation impossible:

MyCat aCat=new MyCat();
aCat.weight=-10.0f;//Set the attribute value of MyCat
float temp=aCat.weight;//Gets the property value of MyCatde

This is because weight is private, so external objects cannot directly access these private properties.

2.3 Setter and Getter methods of private properties

Although it can be encapsulated to achieve the purpose that the outside world cannot access private attributes. But how to solve this contradiction if you have to assign a value to the attribute of the object? Generally, when designing classes, programmers will design public interfaces to store or retrieve these attributes. The external manifestation of these interfaces is (public) methods. In these methods, we can reasonably check the operation of saving or retrieving attributes, so as to achieve the purpose of protecting attribute data. The method of this class can be named as. X0, and the method of this class can be named as any value of. Xxx The method of getting attribute value is usually named Getyyy, where Yyy is any meaningful name. These methods can be collectively referred to as Getter methods.

[example 3-A cat of controllable quality 🐱]

public class TestCat3 {
	public static void main(String[] args) {
		MyCat aCat=new MyCat();
		aCat.SetWeight(-10f);//Set the attribute value of MyCat
		
		float temp=aCat.GetWeight();//Gets the property value of MyCatde
		System.out.println("The weight of a cat is"+temp);
		
	}

}
class MyCat{
	private float weight;//Encapsulate the attributes of MyCat through the private modifier
	public void SetWeight(float wt) {
		if(wt>0) {
			weight=wt;
		}
		else {
			System.out.println("weight Illegal setting (expected)>0).\n Use default values");
			weight =10.0f;
		}
	}
	public float GetWeight() {
		return weight;
	}
}

The operation result is:

[code details]:
1. Add public methods such as Setweight(oatw) and float Getweight0. The outside world can set and obtain the private attribute weight in the class through these interfaces.
2. The Setweight0 method is called and an unreasonable weight of - 10 is passed in at the same time.
3. When setting the weight, the program adds some judgment statements. If the value passed in is greater than 0, assign the value to weight Property, otherwise a warning message is given and the default value is adopted. Through this method, we can see that we can operate on attribute values through public interfaces, and we can "control" these values in these interfaces, so as to better control attribute members.

2.4 packaging and use of method

From this, we can know that attributes can be encapsulated with prvat, and of course, methods can also be encapsulated with private. The form of encapsulation is as follows:

Encapsulation attribute: private attribute type attribute name

Encapsulation method: private method return type method name (parameter)

[example 4 - packaging use of method]

  
public class TestCat4 {
	public static void main(String[] args) {
		MyCat aCat=new MyCat();
		aCat.SetWeight(-10f);//Set the attribute value of MyCat
		
		float temp=aCat.GetWeight();//Gets the property value of MyCatde
		System.out.println("The weight of a cat is"+temp);
		aCat.MakeSound();//Type MakeSound() is not visible
	}

}
class MyCat{
	private float weight;//Encapsulate the attributes of MyCat through the private modifier
	public void SetWeight(float wt) {
		if(wt>0) {
			weight=wt;
		}
		else {
			System.out.println("weight Illegal setting (expected)>0).\n Use default values");
			weight =10.0f;
		}
	}
	public float GetWeight() {
		return weight;
	}
	private void MakeSound() {
		System.out.println("Meow meow,my weight is"+weight);
	}
}

According to the running results, the method MakeSound() in MyCat is not visible. Because the method MakeSound() is set with the permission that can only be accessed in the MyCat class by the private modifier. The correct way is:

public float GetWeight(){
    MakeSound();  //Method call added within method
    return weight;
}

2.5 using constructors to encapsulate data

[example 5]:

public class TestCat5 {
	public static void main(String[] args) {
		MineCat aCat=new MineCat(12,-5);//Set attribute value through public interface
		
		float ht=aCat.GetWeight();
		float wt=aCat.GetHeight();
		System.out.println("The height of cat is"+ht);
		System.out.println("The weight of cat is"+wt);
	}

}
class MineCat{
	private float weight;
	private float height;
	//Initializing private variables in constructors
	public MineCat(float height,float weight) {
		SetHeight(height);
		SetWeight(weight);
	}
	
	private void SetHeight(float ht) {
		if(ht>0) {
			height=ht;
		}
		else {
			System.out.println("Height Illegal setting (expected)>0).\n The default value of 20 is adopted");
		}
	}
	//Create a public method GetHeight() as an interface for communication with the outside world
	public float GetHeight() {
		return height;
	}
	private void SetWeight(float wt) {
		if(wt>0) {
			weight=wt;
		}
		else {
			System.out.println("weight Illegal setting (expected)>0). \n The default value of 20 is adopted");
		}
	}
	public float GetWeight() {
		return weight;
	}
}

2.6 summary of packaging problems

  • In Java, the most basic encapsulation unit is class, which is the basis of object-oriented programming language. Programmers can encapsulate the code with the same business nature in a class, provide services to external code through interface methods, and shield the specific implementation of services in the class to external code.

  • The most important purpose of data encapsulation is to realize "information hiding". In the "data component (attribute)" or "method member" in the class, you can use the keywords "public", "private" and "protected" to set the access rights of each member.

  • Encapsulation is one of the principles of object-oriented programming. It stipulates that objects should hide their internal working methods from the external environment. Good encapsulation can improve the modularity of code and prevent the bad interaction between objects. Make the program achieve the ultimate goal of strong cohesion (many functions are completed independently within the class as far as possible without external intervention) and weak coupling (provide as few method calls as possible to the outside).

3. Succession

Inheritance is an effective means to improve the reusability of program code and the scalability of the system. Inheritance has certain adaptability, and inheritance relationship cannot be established casually in code.

3.1 inheritance in life

In nature, rabbits and sheep are herbivores. They have the basic characteristics and behavior of herbivores. At this time, if herbivores are called "parents", rabbits and sheep are subclasses of herbivores. Similarly, lions and tigers are subclasses of carnivores.

From a large perspective, both carnivores and herbivores have the basic characteristics and behavior of animals. Therefore, the animals at this time are the parent, while herbivores and carnivores are the subclasses.

In the inheritance relationship, the subclass has the characteristics and behavior of the parent class, and also has some special characteristics and behavior of its own. In the inheritance relationship, the parent and child classes need to meet the is-a relationship.

is-a relationship: (subsumption) contains architecture, pure inheritance relationship, Student is a person, Dog is a animal

In addition, it should be reminded that there are various terms that express parent and child classes, such as parent and child classes, superclass and child classes, base class and derived class. They express the same meaning.

3.2 why inheritance is needed?

If there are a lot of duplicate code in two classes. This obviously violates the principle of "Write once,only once" when we do object-oriented programming.

At this time, "inheritance" will begin to show its skills!

We can abstract a parent class from these two classes, extract the properties and methods in both classes into the parent class for implementation, and let the child class automatically inherit these properties and methods.

3.3 how to implement inheritance

In the Java language, the extends keyword is used to indicate that one class inherits another class, for example:

public class JavaTeacher2 extends HZTeacher{ }

This code indicates that the JavaTeacher class inherits HZTeacher

* * note that multiple inheritance is not allowed in Java (but multi-layer inheritance can be used). You can only inherit one class, not multiple classes! The following code is wrong:**

public class Child extends Base1, Base2{ }

Multi level inheritance is as follows:

class A
{   }
class B extends A
{   }
class C extends B
{   }

3.3.1 inheritance demonstration program

public class TestStudent {
	public static void main(String[] args) {
		//Instantiate a Student object
		Student s=new Student("Zhang San",25,"University of Technology");
		s.speak();
		s.study();
				
	}

}
class Person{
	String name;
	int age;
	Person(String name,int age){
		this.name =name;//In order to distinguish the formal parameter with the same name in the constructor Person () from the attribute name in the class, "this" on the left of "=" indicates that the name and age on the left are from the class
		this.age =age;
	}
	void speak() {
		System.out.println("My name:"+name+"I"+age+"year");
	}
}
//Declare a Student subclass with three attribute members: name, age and school; Three methods: Student(), study(), Person()
class Student extends Person{ 
	String school;
	Student(String name,int age,String school){
		//super calls the constructor of the parent class
		super(name,age);
		this.school=school;
	}
	void study() {
		System.out.println("I am here"+school+"read");
	}
}

3.3.2 super VS this

super note

In the construction method of the subclass, the construction method of the parent class is called through the super and this keywords. Note: when creating an object, create a parent object first and a child object later. If the constructor that calls the parent class is not displayed, the parameterless constructor of the parent class will be called automatically.

  1. That is, the statement that calls the parent class construction (i.e. super statement) must be the first statement in the construction method.
  2. super must only appear in subclass methods and construction methods
  3. super and this cannot call construction methods at the same time. They are one of two
super VS this
differencethissuper
Search rangeFirst find the property or method from this class, and then find the parent class if this class cannot find itInstead of querying the properties and methods of this class, the child class directly calls the specified properties and methods of the parent class
Call constructThis calls the constructor of this classCall parent class construction by subclass
specialRepresents the current object------

1. Different representative objects:

This: this object is called by itself

super: represents the application of the parent object

2. Different premises:

this: can be called without inheritance

super: can only be used under inheritance conditions

3. Construction method:

This: the structure of this class

super: Construction of parent class

[error example]
class Base{
    public String name;
    public Base (String pName){
        name=pName;
}
}
class Child extends Base{
    public Child(){
        name="hello";
        super=("child");
    }
}

Analysis: in the constructor of Child class, the constructor of parent class is called with super statement, but it is misplaced!!! Because when creating an object, you must first create a parent object and a Child object.

[example 6 Super calls the construction method of the parent class]
public class SuperDemo {
	 public static void main(String[] args) {
		 Student2 s =new Student2("Jack",30,"HAUT");
		 System.out.println("name:"+s.name+"\tAge:"+s.age+"\tSchool:"+s.school);
	 }

}
class Person2{
	String name;
	int age;
	//Construction method of parent class
	public Person2(String name,int age) {
		this.name=name;
		this.age=age;
	}
}
class Student2 extends Person2{
	String school;
	//Construction method of subclass
	public Student2 (String name,int age,String school) {
		super(name,age);//Call the constructor of the parent class
       /*Equivalent to this name=name;
		       this.age=age;
		*/
		this.school=school;
	}
}
[Example 7-super calls the properties and methods of the parent class]

Call the property or method of the parent class:

super . Keywords in parent class

super. Methods in parent class ()

public class SuperDemo2 {
	 public static void main(String[] args) {
		 Student3 s =new Student3("Jack",30,"HAUT");
		 System.out.println("\t I am from:"+s.school);
	 }

}
class Person3{
	String name;
	int age;
	//Construction method of parent class
	public Person3(){
		
	}
	public String talk() {
		return "I am:"+this.name+"\t I am:"+this.age+"years old";
		
	}
}
class Student3 extends Person3{
	String school;
	//Construction method of subclass
	public Student3 (String name,int age,String school) {
        //Call the attribute in the parent class with super
		super.name=name;
		super.age=age;
		//Here, use super to call the talk() method in the parent class
		System.out.print(super.talk());
		//Call the school property in this class
		this.school=school;
	}
}

4. Polymorphism

4.1 meaning of polymorphism

Polymorphism, literally, means that one type shows multiple states.

In Java, polymorphism is divided into two categories:

  • Method polymorphism is reflected in method overloading and overwriting.
  • Object polymorphism is reflected in the transformation between parent and child objects.

A core concept of polymorphism is that subclass (derived class) objects can be regarded as parent (base class) objects. This is easy to understand. In the inheritance relationship shown in the figure below, fish, bird and horse all inherit from the parent animal. For these instantiated objects, we can say that fish (child object) is an animal (parent object); Birds (subclass objects) are animals (parent objects); Similarly, horses (child objects) are animals (parent objects).

In Java programming, we can use the following figure:

4.2 transformation between parent and child objects

  • Upcast (automatic transformation): parent object = child instance.
    Assign the subclass object to the parent object, which automatically converts the subclass object to the parent object. This conversion is safe. example
    For example, we can say that fish are animals, birds are animals and horses are animals. This upward transformation is widely used in polymorphism.
  • Downcast (forced transition): subclass subclass object = (subclass) parent object.
    Assign a parent object to a child object. This conversion is unsafe. For example, if we say that animals are fish and animals are birds,
    The animal is a horse. This kind of description is not comprehensive. Therefore, in a specific context, if you need to convert a parent object to a child object, you must use
    Cast type. This downward transformation uses less.

[example 8 - understanding polymorphism]

public class Poly {
	public static void main(String[] args) {
		//Here, the parent object is instantiated by the child class
		Person6 p=new Student6();
		//Call fun1() and observe which class fun1() is called here
		p.fun1();
		p.fun2();
	}

}
class Person6{
	public void fun1() {
		System.out.println("fun1()I'm from the parent class Person");
	}
	
	public void fun2() {
		System.out.println("fun2()I'm from the parent class Person");
	}
}

class Student6 extends Person6{
	//fun1() in the parent class is overridden here
	public void fun1() {
		System.out.println("fun1()I come from a subclass Student");
	}
	public void fun3() {
		System.out.println("fun3()I come from a subclass Student");
	}
}

Operation results:

For the statement: Person p= new Student0, we analyze as follows: on the left side of the assignment operator "=", the parent Person object p is defined, while on the right side of the assignment operator "=", a subclass nameless object is declared with "new Student0", and then the subclass object is assigned as the parent object p. in fact, an upward transformation occurs at this time. This example shows that a parent class has only subclasses. This "one-to-one" inheritance mode does not reflect the "many" state.

[Example 9 - use of method polymorphism]

public class Sum {
	void sum1(int i) {
		System.out.println("The numbers and are:"+i);
	}
	void sum1(int i,int j) {
		System.out.println("The numbers and are:"+(i+j));
	}
	public static void main(String[] args) {
		Sum demo = new Sum();
		demo.sum1(1);
		demo.sum1(2,3);
	}

}

Operation results:

For the statement: Person p= new Student0, we analyze as follows: on the left side of the assignment operator "=", the parent Person object p is defined, while on the right side of the assignment operator "=", a subclass nameless object is declared with "new Student0", and then the subclass object is assigned as the parent object p. in fact, an upward transformation occurs at this time. This example shows that a parent class has only subclasses. This "one-to-one" inheritance mode does not reflect the "many" state.

Keywords: Java Programming Polymorphism encapsulation

Added by mikes127 on Tue, 08 Mar 2022 03:02:46 +0200