Encapsulation, inheritance and polymorphism of three features in Java

catalogue

1, Encapsulation

1. Introduction of package

2. Concept of packaging:

3. Access qualifier

(1) How to encapsulate in Java

(2) Code validation access

(3) About how to use modifier encapsulation

3. Use of packaged packages

  (1) Package introduction

(2) Package concept

(3) Use of self-contained packages in Java

  (4) Common packages in Java

(5) How to customize a package

2, Inherit

1. What is inheritance

2. Why should there be inheritance

3. Concept of succession

4. How to realize inheritance

5. Precautions in succession

  6. Precautions when accessing parent class members

(1) The names of parent and child class member variables are the same

(2) The member method name is the same

  (3) If the member variable names are the same, access the member variable of the parent class (super keyword)

(4) Summary

7. Construction method of subclass

(1) Call of construction method

  (2) Similarities and differences between super and this

8. Execution order of code blocks in inheritance

(1) Introduce

(2) Code verification

  (3) Summary

9. Inheritance methods supported in Java

10.final keyword

  11. Inheritance and composition (code reuse)

3, Polymorphism

1. The concept of polymorphism

2. Implementation conditions of polymorphism

3. Code (class example)

  4. Method rewriting and overloading

(1) Method override

  (2) Method overload

5. Upward and downward transformation

(1) What is upward transformation

(2) Code test

(3) What is downward transformation

1, Encapsulation

1. Introduction of package

When you hear packaging, the first thing you think of is that something is packaged. For example, the things in a box are wrapped so that the things in it are not seen.

Let's take a more detailed example, that is, the computer. Generally, we only know how to turn on the desktop computer we buy and use the keyboard and mouse to interact with the computer. However, when the computer really runs, it runs through some hardware devices such as cpu, graphics card and memory, but we can't see these things when we use it, Because these things are encapsulated by manufacturers, they only reveal the basic operations of users.

2. Concept of packaging:

Organically combine the data with the methods of operating the data, hide the attributes (member variables) and implementation details of the object, and only expose the interface to interact with the object.

3. Access qualifier

Before using encapsulation, we must first understand the access qualifier so that encapsulation can be used.

(1) How to encapsulate in Java

Java mainly implements encapsulation through classes and access rights: classes can combine data and methods to encapsulate data, which is more in line with human cognition of things, and access rights are used to control those methods or attributes that need to be used directly outside the class. Four access qualifiers are provided in Java as follows:

(2) Code validation access

  In the same package and category:

 

  In different classes in the same package

  In different classes of different packages

 

  In subclasses of different packages

Note: in general, the member variable is set to private and the member method is set to public.

(3) About how to use modifier encapsulation

Generally, member variables are decorated with private, and member methods are decorated with public. However, the specific use depends on the class to which the member variables in the class are used. If it is a subclass (what subclasses are in the subsequent inheritance), use protected; If the member variable needs to be accessed by all classes, it is set to public; Only by using modifiers properly can members have good encapsulation.

3. Use of packaged packages

  (1) Package introduction

In order to better manage classes in Java, packages are introduced.

(2) Package concept

The collection of multiple classes or into a group is called a software package.

In Java, packages act as folders to manage classes. Package is equivalent to the embodiment of encapsulation of classes and interfaces. For example, a class in a package does not want to be accessed by classes in other packages. If the report is not imported, it cannot be used. Moreover, classes with the same name can exist in different packages.


(3) Use of self-contained packages in Java

There are many ready-made classes in Java for us to use, but we need to import relevant packages before using them. For example, the Arrays class and Date class are used directly after the package is imported. The usage is the same as the class defined by ourselves. The access member method is accessed through.

Here is how to guide and use.

Method 1: before adding the path of the package to the object

public class Demo {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();
        System.out.println(date.getTime());//Milliseconds of print time
    }
}

Method 2: import the package outside the class through the import keyword

import java.util.Date;

public class Demo {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date.getTime());//Milliseconds of print time
    }
}

Which of the two methods is better depends on the scenario.

Note: if you import multiple packages and another package contains a class with the same name, the Java compiler may not know which package you are importing. At this time, use method 1 (before adding the package path to the object); If there is no class with the same name, you can use the second method for convenience.

If you need multiple classes under the util package, you can use import java.util. *; Import them directly.

Here, I use both the Date class and the Arrays class (both of which are under the util package) and use them through the package Guide:

  (4) Common packages in Java

1. java.lang: system common basic classes (String, Object). This package is automatically imported from JDK1.1.
2. java.lang.reflect:java reflection programming package;
3. java.net: network programming development package
4. java.sql: support package for database development.
5. java.util: a tool package provided by java. (set class, etc.) important
6. java.io:I/O programming development kit


(5) How to customize a package

Since there is a package concept in Java, you can also customize the package yourself.

Specific operation:

  Regulations on package naming: in large-scale development, in order to prevent the package name from being the same, different companies generally define it by reversing the company's domain name and adding the package name, such as com.baidu.demo.

After creating a package, folders will be generated under your current project, and the class created under the package will add package + package name in the first line.

2, Inherit

1. What is inheritance

In life, we have many examples of inheritance. For example, a son inherits his father's property, and cats and dogs inherit some characteristics of animals.

2. Why should there be inheritance

If we define a cat and a dog, we will think of their attributes, such as color, name, male and female, and they will sleep and eat. These are the commonalities of animals. If they are written separately, they are equivalent to repetitive codes. Therefore, we think of putting these commonalities into the same animal class, which doesn't need us to do repetitive work.

3. Concept of succession

It is the most important means for object-oriented programming to make code reusable. It allows programmers to maintain the characteristics of original classes (other names: parent class, base class, superclass)
And add new functions, so as to produce a new class, called derived class (subclass). Inheritance presents the hierarchical structure of object-oriented programming and embodies the cognitive process from simple to complex. Inheritance mainly solves the problems of commonness extraction and code reuse.

4. How to realize inheritance

usage method:   Subclass extends parent class

Next, use cats and dogs as examples:

(1) Animals

public class Animal {
    String name;//name
    String color;//colour
    String gender;//male and female
    public void sleep(){
        System.out.println(name+"sleep");
    }
    public void eat(){
        System.out.println(name+"Eat something");
    }
}

(2) Cats  

public class Cat extends Animal{
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.name="Chrysanthemum";
        cat.gender="mother";
        cat.color= "orange";
        cat.eat();
        cat.sleep();
    }
}

  (3) Dogs

public class Dog extends Animal{
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "Xiao Hei";
        dog.gender="common";
        dog.color = "black";
        dog.eat();
        dog.sleep();
    }
}

Cat operation results:

  Dog operation results:

  As can be seen from the above code, we do not define these properties and methods in dog and cat classes, but we can access them by instantiating objects. This is because we inherit the member variable member methods in animal classes. In this regard, animal classes are equivalent to the parent classes of dog and cat, and these two classes themselves are equivalent to children.

5. Precautions in succession

(1) Subclasses inherit only the member variables and member methods of the parent class to.

(2) Subclasses must have their own unique members after inheriting the parent class, otherwise there is no need to inherit.

For the above dog and cat classes, we can add specific member methods for implementation, add a gatekeeper method in the dog class and a mouse catching method in the cat class.

As follows:

 

  6. Precautions when accessing parent class members

We know that subclasses inherit the member variables and methods of the parent class, but sometimes we accidentally define members with the same name as the parent class in the subclass. At this time, we need to know which Java should use and how to use the members in the parent class.

(1) The names of parent and child class member variables are the same

(2) The member method name is the same

  When the method name is the same and the parameter list is the same, the subclass methods will be accessed according to the proximity principle; However, when the method name is the same and the parameter list is different, the method overload will be formed. The specified method can be accessed according to the parameters passed by the calling method.

 

  (3) If the member variable names are the same, access the member variable of the parent class (super keyword)

To access a member variable with the same name as the parent class, use the super keyword.

The purpose of the super keyword is to access the members of the parent class in the non static methods of the child class.

Parent class:

public class Fu {
    int a=1;
    int b=2;
public void testMethod(){
    System.out.println("father");
}
}

Subclass:

public class Zi extends Fu{
    int a=10;
    int b=20;
    int c = 3;
    public void testTemp(){
    super.a=10;
    super.b=20;
    c=30;
    }
    public void testMethod(int count){
        System.out.println("son");
    }
    public static void main(String[] args) {
        Zi zi = new Zi();
        zi.testTemp();
        zi.testMethod();
        zi.testMethod(1);
    }
}

  super keyword precautions:

Can only be used in non static methods

Only member variables and methods of the parent class can be accessed in a subclass method

(4) Summary

In the process of access, priority will be given to searching in the subclass. If it is found, it will be accessed. If it is not found, it will be searched in the parent class. If it is found, it will be accessed. If it is not found, an error will be reported.

In the process of access, if you use the same name directly, you will access according to the proximity principle. The method is slightly different.

7. Construction method of subclass

(1) Call of construction method

In the concept of inheritance, we know that a subclass inherits only the member variables and methods of the parent class, so how is the construction method defined.

When constructing a subclass object, the construction method of the subclass will be called first. In the construction method of the subclass, the first sentence is to call the construction method of the parent class for verification through code.

  We do not construct the parent class object here. Why does the compiler call the construction method of the parent class? This is because the child class object is also a parent class object. When constructing the child class object, first initialize the members inherited from the parent class, and then initialize the newly added members of the child class.

Simple description through object model:

 

The precondition for automatically calling the parent class constructor is that the parent class constructor is parameterless. If there are parameters, the compiler cannot call it automatically. At this time, we need to call it manually and pass it to the specified parameters.

As follows:

Not called manually:

  Manual call:

  (2) Similarities and differences between super and this

  1. Similarities

  1. Are keywords in Java.
  2. It can only be used in non static methods of a class to access non static member methods and fields.
  3. When invocation in a construction method, the first statement in the method must be constructed, and it can not exist at the same time.

2. Differences

  1. Different reference objects: this is the reference of the current object, which is the object calling the instance method, and super is the reference of the parent object.
  2. this is the reference of the current object. The current object is the object that calls the instance method. super is equivalent to the reference of the parent object.
  3. this is a hidden parameter of a non static member method, and super is not a hidden parameter.
  4. When directly accessing members of this class in member methods, this will be restored after compilation, that is, non static members of this class are accessed through this; In the subclass, if the parent class member is accessed through super, super does not exist at the bytecode level after compilation.
  5. In the construction method: this(...) is used to call the construction method of this class, and super(...) is used to call the construction method of the parent class. The two calls cannot appear in the construction method at the same time.
  6. There must be a call to super(...) in the constructor. If the user does not write, the compiler will increase, but if the user does not write this(...), it will not.

8. Execution order of code blocks in inheritance

(1) Introduce

In classes and objects, we know that static code blocks in code blocks are executed first, and no matter how many objects are created, they are executed only once, followed by instance code blocks, and finally construction methods. So how is it executed in the inheritance system.

(2) Code verification

public class Test {
    public static void main(String[] args) {
    Student student1 = new Student("Zhang San",18,"male");
        System.out.println("################");
        Student student2 = new Student("Xiao Hong",16,"female");


    }
}
class Person{
    String name;
    int age;
    String gender;
    {
        System.out.println("Person Instance code block");
    }
    static{
        System.out.println("Person Static code block");
    }
    public Person(String name, int age, String gender) {
        System.out.println("Person constructor ");
    }
}
class Student extends Person{
    {
        System.out.println("Student Instance code block");
    }
    static {
        System.out.println("Student Static code block");
    }
    public Student(String name, int age, String gender) {
        super(name, age, gender);
        System.out.println("Student constructor ");
    }
}

Operation results:

  (3) Summary

  In the inheritance system, the running order is: parent class static code block, child class static code block (both static code blocks are executed only once during class loading), parent class instance code block, parent class construction method, child class instance code block and child class construction method.

9. Inheritance methods supported in Java

  Note: Although a class can inherit from multiple layers, it generally does not exceed three layers. If there are too many inheritance layers, you need to consider refactoring the code, because the more layers, the more complex the code structure.

10.final keyword

(1) Purpose of final: used to modify variables, methods and classes.

(2) Action result of final

Modify variable: variable cannot be modified.

  Modifier method, method cannot be overridden (overridden in polymorphic introduction)

 

 

  Decorated class, class cannot be inherited:

  11. Inheritance and composition (code reuse)

  We already know that inheritance can achieve code reuse, but we generally do not recommend using inheritance to achieve reuse unless the class has an is-a relationship: for example, a dog is an animal and a cat is an animal.

In the process of programming, we generally use combination to realize code reuse. For combination, it is the relationship of has -a: for example, there are tires, engines, steering wheels and so on in cars. Obviously, there is no strong inheritance relationship between the car and the things inside. It is obviously inappropriate to use inheritance, so we can use combination for implementation. The following code is an example:

public class BMWCar extends Car{
    String color;
    
}
//Automobile
class Car{
    protected SteeringWheel steeringWheel;
    protected Engine engine;
    public void Start(){
        engine.start();
        steeringWheel.turn();
    }
    public void Stop(){
        engine.stop();
    }

}
//Steering wheel
class SteeringWheel{
    public void turn(){
        System.out.println("Turn the steering wheel");
    }

}
//Engine class
class Engine{
    public void start(){
        System.out.println("Engine start");
    }
    public void stop(){
        System.out.println("Engine shutdown");
    }
}

 

  To sum up, it is recommended to use combination for code reuse.

3, Polymorphism

1. The concept of polymorphism

Generally speaking, it is a variety of forms. Specifically, it is to complete a certain behavior. When different objects complete it, they will produce different states. For example, when cats and dogs eat this behavior, they will have different states. Cats eat cat food and dogs eat dog food; For the behavior of going to the classroom, the teacher goes to class and the students go to class. Therefore, polymorphism occurs.

In a word, if the same thing happens to different objects, it will produce different results.

2. Implementation conditions of polymorphism

Now that we know what polymorphism is, we need to know the conditions and limitations for implementing polymorphism.

(1) Under the inheritance system

(2) Subclasses need to override parent methods

(3) Call the overridden method through the reference of the parent class

3. Code (class example)

public class ClassRoom {
    public static void testInClass(Person person){
        person.inClass();
    }
    public static void main(String[] args) {
        Teacher teacher = new Teacher();
        Pupil pupil = new Pupil();

        //Call different overrides by passing different objects to testInClass(person)
        testInClass(teacher);
        testInClass(pupil);
    }
}
//teacher
class Teacher extends Person{
    public void inClass(){
        System.out.println("Teacher attend class;class begins");
    }
}
//student
class Pupil extends Person{
    public void inClass(){
        System.out.println("Pupil attend class;class begins");
    }
}
//people
class Person{
    public void inClass(){
        System.out.println("Person attend class;class begins");
    }
}

Operation results:

  In this example, by rewriting the inClass() method in the subclass of the parent class Person and calling the inClass() method in testInClass(..), different behaviors are realized through different objects. This behavior is called polymorphism.

  4. Method rewriting and overloading

(1) Method override

In polymorphism, we know that one of the conditions is method rewriting, so we need to know what method rewriting is and how to implement method rewriting.

1.1 concept of method Rewriting:

Also called overlay. Rewriting is the implementation process of a subclass's non static, non private modification, non final modification, non constructor, etc. of its parent class
When rewriting, the return value and formal parameters cannot be changed, but only the contents of the method can be changed.

Code validation:

(1) For static methods, they can be accessed directly through the class name, which does not reflect rewriting

(2) priavte decorated cannot be overridden

(3) Constructor cannot be overridden

(4) Modified by final and cannot be overridden


1.2 notes for rewriting:

(1) must as like as two peas, except for the content in the method.

(2) After jdk7, the return value type can be a class type with parent-child relationship

(3) The access modifier of an overriding method in a subclass cannot be lower than the permission of a parent method.

Access permissions from large to small: public > Default > protected (do not use private)

  (4) You can verify whether it is overridden through the @ Override annotation.

(5) Design principles of rewriting; The classes that have been put into use should not be modified as much as possible. You can define a new class to override the old class methods, because it is more user-friendly.

  (2) Method overload

Concept of overloading: the method name is the same, but the parameter list of the method is different.

Different parameter lists include: return value types, order of types, and number of parameters

Because the compiler will automatically deduce the argument type and determine which method the user calls according to the deduction, method overloading can be formed.

For example:

public class TestOverload{
    //    The test method has different parameter lists and the same method name, which implements overloading
    public void test(){
        
    }
    public void test(int a){
        
    }
}

Precautions for heavy load:

Overloading has nothing to do with the type of return value. Only different types can not constitute overloading

  (3) The difference between overloading and rewriting

differenceheavy loadrewrite
parameter listCan be modifiedCannot be modified
return typeCan be modifiedCannot be modified (it can be modified to a class type with inheritance relationship)
Access qualifierCan be modifiedCan reduce the limit
abnormalCan be modifiedIt can be reduced or deleted, and new or broader exceptions cannot be thrown (temporarily ignored)

  Conclusion: for overloading and rewriting, polymorphism is reflected.

Overloading reflects the polymorphism of a class, where overloading belongs to static binding

Rewriting reflects the polymorphism between subclasses and parent classes. Here rewriting belongs to dynamic binding

The concept of static binding: that is, when compiling, the method to be called is determined according to the actual parameter type passed by the user.

Dynamic binding concept: that is, the behavior of the method cannot be determined at compile time, and the specific method can be determined only when the program is running
Call methods of that class.

5. Upward and downward transformation

The concept of transformation appears in the rewriting of methods to realize polymorphism.

(1) What is upward transformation

In fact, it is to create a subclass object and use it as a parent object.

Format: parent type   Object name   = new subclass type

(2) Code test

public class OverrideAccess {
    public static void main(String[] args) {
        Father father = new Son();//This is the upward transformation

    }
}
class Father{
    public Father test(){
    return new Father();
    }

}
class Son extends Father{

}

Because the subclass object is a parent object, the subclass object can be used as the parent object, and the upward transformation is safe without any problem.

Note: the return value type can also be transformed upward:

Code test:

testReturn () reflects the upward transformation.

public class OverrideAccess {
    public Father testReturn(String str){
        if(str=="Father"){
            return new Father();
        }if(str=="Son"){
            return new Son();
        }
        else {
            return null;
        }
    }
    public static void main(String[] args) {
        

    }
}
class Father{
    public Father test(){
    return new Father();
    }

}
class Son extends Father{

}

Although the upward transformation makes the code more flexible, we can't access the unique methods in the subclass. We can only access the methods overridden by the subclass in the parent class.

(3) What is downward transformation

1. Concept: the process of restoring a parent object to a child object.

2. Note: we know that subclasses belong to the parent class and can be transformed upward at will, but the parent class is not necessarily a subclass. For example, cats are animals, so there is no problem; But if an animal is a cat, there will be problems.

Code example:

public class ClassRoom {
    public static void main(String[] args) {
        Teacher teacher = new Teacher();
        Pupil pupil = new Pupil();
        Person person  =teacher;//Upward transformation
        person.inClass();
        person = pupil;
        person.inClass();
        teacher = (Teacher) person;//Strong downward rotation
        teacher.work();

    }
}
//teacher
class Teacher extends Person{
    public void inClass(){
        System.out.println("Teacher attend class;class begins");
    }
    public void work(){
        System.out.println("The teacher wrote the lesson plan");
    }
}
//student
class Pupil extends Person{
    public void inClass(){
        System.out.println("Pupil attend class;class begins");
    }
    public void homework(){
        System.out.println("Students do their homework");
    }
}
//people
class Person{
    public void inClass(){
        System.out.println("Person attend class;class begins");
    }
}

  In the above downward transformation, there is a security problem. In order to solve the problem of downward transformation, Java introduces instanceof to true to judge whether downward transformation can be carried out.

The usage is as follows:

If (parent object instanceof child class name){

The transformed statements and the methods that need to call subclasses

}

Code demonstration:

public class ClassRoom {
    public static void main(String[] args) {
        Teacher teacher = new Teacher();
        Pupil pupil = new Pupil();
        Person person  =teacher;//Upward transformation
        person.inClass();
        person = pupil;
        person.inClass();
 
        //Downward transformation modified results
        if(person instanceof Pupil){//Judge whether it can be transformed downward
            pupil = (Pupil) person;
            pupil.homework();
        }
        if(person instanceof Teacher){
            teacher = (Teacher) person;
            teacher.work();
        }

    }
}
//teacher
class Teacher extends Person{
    public void inClass(){
        System.out.println("Teacher attend class;class begins");
    }
    public void work(){
        System.out.println("The teacher wrote the lesson plan");
    }
}
//student
class Pupil extends Person{
    public void inClass(){
        System.out.println("Pupil attend class;class begins");
    }
    public void homework(){
        System.out.println("Students do their homework");
    }
}
//people
class Person{
    public void inClass(){
        System.out.println("Person attend class;class begins");
    }
}

 

 

Tags: Java Algorithm

Posted by me1000 on Mon, 20 Sep 2021 11:22:53 +0530