Java Basics Review Part 3 - Encapsulation, Inheritance and Polymorphism

foreword

In the previous article, I reviewed the modifiers and String classes of Java. This article will review the three major features of Java: encapsulation, inheritance, and polymorphism.

package

what is encapsulation

In object-oriented programming, encapsulation refers to a method of wrapping and hiding the implementation details of an abstract functional interface.

Encapsulation can be thought of as a protective barrier that prevents the code and data of that class from being randomly accessed by code defined by the outer class. Access to the code and data of this class must be controlled through a strict interface.

The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code. Proper encapsulation can make the code easier to understand and maintain, and it also enhances the security of the code.

Simply put, it is to encapsulate frequently used code in Java to form a method. For example, our commonly used entity classes use private to modify variables to protect data; external getter and setter methods are provided for invocation. This is a typical package.

Code sample :

    public class packagingTest {

        public static void main(String[] args) {
            User user=new User();
      //这里会报错,因为id和name是私有的,用于保护该数据
    //      user.id=10;
    //      user.name="张三";
            user.setId(1);
            user.setName("张三");
            System.out.println(user.getId());
            System.out.println(user.getName());
        }

    }

    class User{
        private int id;
        private String name;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

operation result:

    1
    张三

The benefits of using encapsulation

  1. Good encapsulation reduces coupling.

  2. The structure inside the class can be freely modified.

  3. Member variables can be controlled more precisely.

  4. Hide information, implementation details.

inherit

what is inheritance

Inheritance is a cornerstone of Java object-oriented programming techniques because it allows the creation of hierarchical classes.
Inheritance means that a subclass inherits the characteristics and behaviors of the parent class, so that the object (instance) of the subclass has the instance fields and methods of the parent class, or the subclass inherits methods from the parent class, so that the subclass has the same behavior as the parent class.

Inherited Features

  • The subclass has the non-private properties and methods of the parent class.
  • Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
  • Subclasses can implement the methods of the superclass in their own way.

Why use inheritance

The main purpose of inheritance is to reuse code! Simply put, it is to extract the repeated code, put it in the parent class, and then inherit it from the subclass. The subclass can also extend the parent class. Therefore, in the inheritance relationship, it can be understood that the parent class is more general, and the subclass is more specific.

For example, in the animal world, cats and lions belong to the cat family, while dogs and wolves belong to the canine family. And they are all animals. Cats and lions have a common parent cat family , and cats and dogs have a common parent animal . So they are in line with inheritance, but they behave differently. Cats and dogs both eat and sleep, but cats can climb trees, dogs can't.
Here, we can use the following code to illustrate.

Code example:

public class extendTest {

    public static void main(String[] args) {
        Cat cat=new Cat();
        Dog dog=new Dog();
        cat.eat();
        cat.sleep("cat");
        cat.climbTree();
        dog.eat("dog");
        dog.sleep("dog");
    }
}

class  Animal{
    public void eat(String name){
        System.out.println(name+"正在吃东西...");
    }
    public void sleep(String name){
        System.out.println(name+"正在睡觉...");
    }
}

class Cat extends Animal{
    private String name="Cat";
    public void eat(){
        super.eat(name);
        System.out.println(name+"吃完了");
    }
    public void sleep(){
        this.sleep(name);
    }

    public void sleep(String name){
        System.out.println(name+"刚刚睡觉!");
    }

    public void climbTree(){
        System.out.println(name+"正在爬树!");
    }
}

class Dog extends Animal{

}

operation result:

Cat正在吃东西...
Cat吃完了
cat刚刚睡觉!
Cat正在爬树!
dog正在吃东西...
dog正在睡觉...

In the above code, the parent class Animal implements the eat and sleep methods, and the subclasses Cat and Dog use the extends keyword to inherit the parent class Animal. The subclass Dog does nothing after inheriting the parent class Animal, while the subclass Cat not only inherits the parent class Animal, but also adds the climbTree method, and also rewrites the eat and sleep methods of the parent class.
In the subclass Cat, two keywords appear: super and this .
The meanings of these two keywords are as follows:

  • super keyword: implements access to the members of the parent class, which is used to refer to the parent class of the current object.
  • this keyword: a reference to itself.

In the above code, the subclass Cat uses the super keyword to call the eat method of the parent class Animal, and uses the this keyword to call the sleep method in this class.

When it comes to inheritance, we have to mention these things: final and protected modifiers, constructors, and upcasting!
The final and protected modifiers have been explained in the last Java modifier and String class , and they are briefly described here.

  • final: The decorated class cannot be inherited.
  • protected: The decorated class is only visible to the class and all subclasses within the same package.

Constructor

Although subclasses can inherit the properties and methods of the parent class (except those modified by private), there is one thing that subclasses cannot inherit, and that is the constructor ! For constructors, it can only be called, not inherited. If the subclass wants to use the superclass's constructor, just use the super keyword to call it.

Note: If the constructor of the parent class is modified by private, it cannot be called externally, including subclasses!

Upward transformation

Converting a subclass to a parent class moves upward in the inheritance relationship, so it is generally called upward transformation.
In the previous example, cats and animals belong to an inheritance relationship, then we can treat cats as animals, which is an upward transformation!
For example:

public class extendTest {

    public static void main(String[] args) {
        Animal animal=new Cat();
        animal.eat("cat");
        animal.sleep("cat");
    }
}

class  Animal{
    public void eat(String name){
        System.out.println(name+"正在吃东西...");
    }
    public void sleep(String name){
        System.out.println(name+"正在睡觉...");
    }
}

class Cat extends Animal{
private String name="Cat";
    public void eat(){
        super.eat(name);
        System.out.println(name+"吃完了");
    }
    public void sleep(){
        this.sleep(name);
    }

    public void sleep(String name){
        System.out.println(name+"刚刚睡觉!");
    }

    public void climbTree(){
        System.out.println(name+"正在爬树!");
    }
}

operation result:

cat正在吃东西...
cat刚刚睡觉!

The above code completes the upward transformation, but there are some shortcomings in the upward transformation, that is, the loss of properties and methods. For example, the climbTree() method and the name attribute in the Cat class are missing in the above code. So use upward transformation with caution!

multiple inheritance

Java's inheritance is single inheritance, but multiple inheritance can be achieved!
Although a subclass can only inherit from one parent class, subclasses of subclasses can also subclass.
For example, class C inherits class B, and class B inherits class A, so according to the relationship, class A is the parent class of class B, and class B is the parent class of class C.

Disadvantages of inheritance

Although inheritance greatly improves the reusability of code, it also improves the coupling between classes! When the parent class changes, the child class must change! So it can be said that inheritance destroys encapsulation because its implementation details are transparent to both the parent class and the child class.
So use inheritance with caution! ! !

polymorphism

What is polymorphism

Polymorphism refers to the existence of different states of things during operation.

Polymorphism means that the specific type pointed to by a reference variable defined in the program and the method call issued through the reference variable are not determined during programming, but are determined during program execution.

Necessary conditions for using polymorphism

There are three necessary conditions for polymorphism to exist:

  1. have an inheritance relationship;
  2. The subclass should override the method of the superclass;
  3. The parent class reference points to the child class object, that is, upcasting.

Simple example of polymorphism usage

In the above inheritance explanation, we used the relationship between cats and animals. We can also use this here. We only need to change the code slightly to achieve polymorphism.

Code example:

public class Test {

    public static void main(String[] args) {
        Animal animal=new Cat();
        animal.eat();
    }
}

class  Animal{
    private String name="Animal";
    public void eat(){
        System.out.println(name+"正在吃东西...");
        sleep();
    }
    public void sleep(){
        System.out.println(name+"正在睡觉...");
    }
}

class Cat extends Animal{
    private String name="Cat";
    public void eat(String name){
        System.out.println(name+"吃完了");
        sleep();
    }
    public void sleep(){
        System.out.println(name+"正在睡觉");
    }
}

Output result:

Animal正在吃东西...
Cat正在睡觉

After seeing the results of the operation, if you are not familiar with polymorphism, do you feel a little strange?
The first sentence printed should be easy to understand. Why is the second sentence printed not the method of Animal, but the method in Cat?

We know that polymorphism refers to the existence of different states of things in the process of running. And here, we use inheritance, overriding, and upcasting.
By the way here:

In upcasting, a parent class reference can point to multiple subclass objects, so the same message at runtime is determined by the actual type of the referenced object.

Based on the above understanding, let's look at the example just now.
In the Cat class, the sleep method of the parent class Animal is overridden, and the eat method is overridden. The overloaded eat(String name) method is not the same method as the eat() method of the parent class Animal, because it will be lost in the upward transformation. The Cat subclass rewrites the sleep method, so it will not be lost when upcasting, and because the specified reference type to the object is Cat, when Animal calls the eat() method, it first calls eat in this class () method, and then call the sleep() method in the subclass!

in conclusion:

When the parent class refers to the subclass method, the methods existing in the parent class must be called. If the method is overridden in the subclass, the method in the subclass will be dynamically called at runtime. This is polymorphism .

Advantages of using polymorphism

Excerpted from: https://www.cnblogs.com/jack204/archive/2012/10/29/2745150.html

  1. Substitutability. Polymorphism enables replaceability of existing code. For example, polymorphism works for the Circle class, as well as for any other circular geometry, such as a torus.
  2. Extensibility. Polymorphism is extensible to code. Adding new subclasses does not affect the operation and operation of existing classes' polymorphism, inheritance, and other features. In fact, it is easier to obtain polymorphism by adding subclasses. For example, it is easy to add polymorphism for the sphere class based on the realization of the polymorphism of cone, half cone, and hemisphere.
  3. interface-ability. Polymorphism is achieved by superclasses providing a common interface to subclasses through method signatures, which can be improved or overridden by subclasses.
  4. Flexibility. It embodies flexible and diverse operations in application and improves the efficiency of use.
  5. Simplicity. Polymorphism simplifies the code writing and modification process of application software, especially when dealing with the operation and operation of a large number of objects, this feature is particularly prominent and important.

After you have a certain understanding of polymorphism, you can try to look at the following code.
This is a classic polymorphism problem, taken from:
http://blog.csdn.net/thinkGhoster/archive/2008/04/19/2307001.aspx

Code example:

    public class extendsTest {  
    public static void main(String[] args) {  
        A a1 = new A();  
        A a2 = new B();  
        B b = new B();  
        C c = new C();  
        D d = new D();  

    System.out.println("1--" + a1.show(b));  
    System.out.println("2--" + a1.show(c));  
    System.out.println("3--" + a1.show(d));   
    System.out.println("4--" + a2.show(b));   
    System.out.println("5--" + a2.show(c));  
    System.out.println("6--" + a2.show(d));  
    System.out.println("7--" + b.show(b));
    System.out.println("8--" + b.show(c));
    System.out.println("9--" + b.show(d));
     }  
    } 

    class A {  
    public String show(D obj) {  
    return ("A and D");  
    }  

    public String show(A obj) {  
    return ("A and A");  
    }   

    }  

     class B extends A{  
    public String show(B obj){  
    return ("B and B");  
    }  

    public String show(A obj){  
    return ("B and A");  
    }   
    }  

     class C extends B{  

    }  

     class D extends B{  

    }  

operation result:

1--A and A
2--A and A
3--A and D
4--B and A
5--B and A
6--A and D
7--B and B
8--B and B
9--A and D

analyze

①②③It is easy to understand and generally can’t go wrong. ④⑤ is a bit confused, why isn't the output "B and B"? ! ! Let's review polymorphism first.

Runtime polymorphism is one of the most powerful mechanisms for code reuse in object-oriented programming, and the concept of dynamism can also be said as "one interface, many methods". The foundation of Java's implementation of runtime polymorphism is dynamic method dispatch, which is a mechanism for calling overloaded methods at runtime rather than at compile time.

Overriding and overloading of methods are different manifestations of Java polymorphism.

Overriding Overriding is a manifestation of polymorphism between parent and child classes, and overloading Overloading is a manifestation of polymorphism in a class. If a method is defined in a subclass with the same name and parameters as its parent class, we say the method is overriding (Overriding). When an object of the subclass uses this method, the definition in the subclass will be called, and for it, the definition in the superclass is "masked". If multiple methods with the same name are defined in a class, and they either have different parameter numbers or different parameter types, it is called method overloading. Overloaded methods can change the type of the return value.

When the superclass object reference variable refers to the subclass object, the type of the referenced object rather than the type of the reference variable determines whose member method is called, but the called method must be defined in the superclass, that is Methods that are overridden by subclasses. (But if you force the superclass to be a subclass, you can call new methods in the subclass that the superclass doesn't have.)

Well, let’s review here first, let’s get down to business! In fact, this involves the priority of method calls. The priority is from high to low: this.show(O), super.show(O), this.show((super)O), super.show((super) O). Let's see how it works.

For example, ④, a2.show(b), a2 is a reference variable, the type is A, then this is a2, and b is an instance of B, so it went to class A to find the show(B obj) method, but could not find it, so Go to the super (superclass) of A, and A has no superclass, so go to the third priority this.show((super)O), this is still a2, where O is B, (super)O is (super) )B is A, so it looks for the show(A obj) method in class A. Class A has this method, but since a2 refers to an object of class B, B overrides the show(A obj) method of A, So finally lock to show(Aobj) of class B, the output is "B and A".

Another example is ⑧, b.show(c), b is a reference variable, the type is B, then this is b, and c is an instance of C, so it goes to class B to find the show(C obj) method, if it is not found, turn to And look for it in B's superclass A, and A does not have it, so it also goes to the third priority this.show((super)O), this is b, O is C, (super)O is (super)C That is, B, so it looks for the show(Bobj) method in B and finds it. Since b refers to an object of class B, it is directly locked to show(B obj) of class B, and the output is "B and B".

According to the above method, other results can be obtained correctly.
The problem continues, and now let's look at how the above analysis process reflects the connotation of the sentence in blue font. It says: When a superclass object reference variable references a subclass object, the type of the referenced object, not the type of the reference variable, determines whose member method is called, but the called method must be defined in the superclass, That is, methods that are overridden by subclasses. Let's take a2.show(b) as an example.

a2 is a reference variable of type A, which refers to an object of B, so this sentence means that B decides which method to call. So it should call show(B obj) of B to output "B and B". But why does it not match the results obtained in the previous analysis? ! The problem is that we don't ignore the second half of the blue font, where it is specifically stated: the method to be called must be defined in the superclass, that is, the method that is overridden by the subclass.

Is show(B obj) in B defined in superclass A? no! Not to mention being covered. In fact this sentence hides a message: it is still determined by the priority of method calls. It finds show(Aobj) in class A, and if subclass B does not override the show(A obj) method, then it calls A's show(Aobj) (because B inherits A, although this method is not overridden, but from super Class A inherits this method, in a sense, it is still determined by B to call the method, but the method is implemented in A); now subclass B overrides show(A obj), so it finally locks to B's show(A obj). That's what that sentence means.

other

Reference:
http://blog.csdn.net/thinkGhoster/archive/2008/04/19/2307001.aspx
https://www.cnblogs.com/jack204/archive/2012/10/29/2745150.html
https: //blog.csdn.net/chenssy/article/details/12786385

At this point, this article is over, thank you for reading! Comments and likes are welcome, your support is the biggest motivation for my writing!
Copyright statement:
Author: Nothingness
Blog Garden Source: http://www.cnblogs.com/xuwujing
CSDN Source: http://blog.csdn.net/qazwsxpcm    
Personal Blog Source: http://www.panchengming.com

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325633481&siteId=291194637
Recommended