Basic features of object-oriented language

Posted by pqdrummer on Thu, 28 Oct 2021 08:15:23 +0200

 


Encapsulation:

Syntax: use private keywords to modify fields and methods (construction methods can also be modified by private)

Meaning: Security (fields and methods modified by private can only be used in the current class). For the caller of the class, the use cost is reduced


Inheritance:

Syntax: Class   Subclass (derived class) extends parent class (base class, superclass) {}. Is to extract the commonness of the class, and then use the extends keyword to implement inheritance (a relationship of... is a...)

Advantage: code can be reused

Note: 1.java subclasses can only inherit one parent class (single inheritance) through the extends keyword

            2. The subclass inherits all the properties and methods of the parent class (except static methods and properties)

            3. When the attribute or method in the subclass object has the same name as the method in the parent object, it is preferred to call its own method

            4. To construct a subclass object, first construct it for the parent object. All constructed objects must be constructed through construction methods

            5. Neither super nor this can be used in static methods

super keyword: refers to the reference of its parent class object inside the child class object (it must be placed in the first line when calling the construction method)

                        super can only point to the direct parent class and cannot represent the indirect parent class

1.super.data     // Represents a member variable that accesses the parent class

2.super.func()   // Represents a member method that accesses a parent class

3.super()          // Represents the constructor that accesses the parent class

this keyword: the reference of the current object

1.this.data     // Represents a member variable that accesses the current object

2.this.func()   // Represents a member method that accesses the current object

3.this()          // Represents the constructor that accesses the current object

Difference between super and this:

differencethissuper
1conceptAccess the properties and methods of this classThe properties and methods of the parent class are accessed by subclasses
2Search rangeFind this class first. If this class does not, call the parent classInstead of looking up this class, you can directly call the parent class without adding definitions
3specialRepresents the current objectnothing

Protected keyword: for subclasses of a class and other classes in the same package, the fields and methods modified by protected are accessible

Scope of application of access modifier qualifier:

Rangeprivate

default

protectedpublic
1The same class in the same package
2Different classes in the same package
3Subclasses in different packages
4Non subclasses in different packages

default: package access permission modifier (nothing is written in the code), such as member attribute int age;

Multi level inheritance (specify a maximum of three):

class A{
    public int a;
}
class B extends A{

}
//It is specified that the class modified by final cannot be inherited
final class C extends  B{
    public void func(){
        System.out.println(super.a);//Represents a super in B, which can only point to its most direct parent class, but cannot represent an indirect parent class
    }
}

final keyword: can modify a variable to represent a constant, indicating that the constant cannot be modified;

                      You can modify a class, called a sealed class, to indicate that the class cannot be inherited;


Combination:

Thought: it is a part of... Or has a

class Student{
    
}
class Teacher{
    
}
class School{
    public Student[] student;//How many students are there in the school
    public Teacher[] teacher;//There are several teachers in the school
}
class Money{
    
}
class Person{
    public Money money;//People have money, which is also a combination
}

Syntax: composition is to take an instance of one class as a field of another class


Polymorphism:

Upward transformation

Concept: a reference of a subclass object to a parent class is called an upward transformation (or a reference of a parent class points to an instance of a subclass)

class Animals{
    protected String name;//null
    protected int age;//0
    public void eat(){
        System.out.println(name+" eat()");
    }

    public Animals(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
class Dog extends Animals{
    public Dog(String name,int age){
        super(name,age);//Access parent class constructor
    }
    
}
class Bird extends Animals{
    public String selfFiled;
    public Bird(String name,int age,String selfFiled){
        super(name,age);//The constructor called by super must be placed on the first line
        this.selfFiled=selfFiled;
    }

    public void fly(){
        System.out.println(name+" fly()︿( ̄︶ ̄)︿");
    }
}
public class TeatDemo{
    public static void main(String[] args) {
        /*Dog dog=new Dog("xiaogou",1);
        Animals animals=dog;//The upward transformation refers to the reference of the child class object to the reference of the parent class object*/
        //The upward transformation classification refers to the subclass object
        Animals animals=new Dog("xiaogou",2);
        animals.eat();
        Animals animals2=new Bird("Bird",3,"self");
        animals2.eat();
        //animals2.fly(); / / only properties and methods specific to the parent class can be accessed, but not those specific to the child class
    }

Note: after the upward transformation, you can only access the properties and methods unique to the parent class through the reference of the parent class, but not the properties and methods unique to the child class

Timing of upward Transformation:

1. Direct assignment (example above)                         

  2. Method transmission

 public static void func(Animals animals){
        animals.eat();
    }

    public static void main(String[] args) {
        Dog dog=new Dog("xiaogou",2);
        func(dog);
        Bird bird=new Bird("Bird",1,"self");
        func(bird);
    }

  3. Method return

public static Animals func2(){
        Dog dog=new Dog("xiaogou",1);
        return dog;
    }

    public static void main(String[] args) {
        func2().eat();
    }

Downward transformation

Concept: reference the parent class object to the child class object

Downward transition unsafe

public static void main(String[] args) {
        Animals animals2=new Bird("Bird",3,"self");
        animals2.eat();
        //The downward transformation refers the parent object to the child object
        Bird bird=(Bird)animals2;//Cast type to Bird type
        bird.fly();
        System.out.println("=======Downward transition unsafe======");
        Animals animals=new Dog("xiaogou",2);
        if(animals instanceof Bird) {//The fly method can only be called if animals is a Bird class
            Bird bird1 = (Bird) animals;
            bird1.fly();//Let the Dog fly, but there is no fly method in the Dog class, and type conversion exceptions will occur, so the Dog can't fly
        }
    }

No if statement

  Add an if statement (no error will be reported), and you must judge the downward transformation

  Instanceof: judge whether an instance references an object, such as animals instanceof Bird

Method override / override / override

1. Same function name

2. The parameter list of the function is the same (number, type)

3. The return value of the function is the same (it can be different, but the return value should form the relationship between parent and child classes -- > covariant type)

Note: 1. Static methods cannot be overridden

            2.private cannot be rewritten

            3. The access permission of the subclass should be greater than that of the parent class

            4. If a method is final ly modified (sealed method), the method cannot be rewritten

//Animals
public void eat(){
        System.out.println(name+" eat()");
    }
//Dog
public void eat(){
        System.out.println("Dog::eat()");
    }

The difference between overloading and rewriting

differenceoverloadoverride
1conceptThe method name is the same, the number and type of parameters are different, and the return value is not requiredThe method name, number and type of parameters and return value type are identical
2RangeA classInheritance relationship
3limitNo permission requirementsOverridden methods cannot have more stringent access control permissions than the parent class

Runtime binding

Conditions to be met: 1. Whether there is upward transformation

                              2. Call the override method with the same name of the parent and child classes through the parent class reference. At this time, runtime binding will occur(                             Bound is the method of the subclass with the same name as the parent class)

public static void main(String[] args) {
        Animals animals=new Dog("xiaogou",2);
        animals.eat();//The runtime binding occurs and the eat method of the subclass Dog is called
    }

When compiling, it is still the eat method of Animals, and when running, it becomes the eat method of Dog

  Polymorphic ideas:

The parent class reference refers to the child class object, and the parent class reference calls the override method of the same name of the parent class and the child class. At this time, if the child class object referenced by the parent class reference is different and the overridden method is called, its expression is also different

//Print multiple shapes
class Shape{
    public void draw(){

    }
}
class Circle extends Shape{
    public void draw(){
        System.out.println("○");
    }
}
class Flower extends Shape{
    public void draw(){
        System.out.println("❀");
    }
}
public class TestDemo3 {
    public static void drawMap(Shape shape){
        shape.draw();
    }
    public static void main(String[] args) {
        Circle circle=new Circle();
        drawMap(circle);
        Flower flower=new Flower();
        drawMap(flower);
    }
}

  

1. Only through a shape.draw);

2. The parameters passed are different, and the parameters representing this reference are different

3. Call the same method through this reference, showing different forms

Method of invocation in a construction method (a pit)

Runtime binding occurs, and the overriding method of the subclass is called

Advantages of polymorphism:

1. The cost of using the class by the caller of the class is further reduced

2. It can reduce the "circle complexity" of the code and avoid using a large number of if else statements

 public static void drawMap(Shape shape){
        shape.draw();
    }

    public static void main(String[] args) {
        Shape[] shapes={new Circle(),new Rectangle(),new Flower()};
        for (Shape shape:shapes) {
            shape.draw();
        }
    }

3. Strong scalability

Topics: Java Back-end