Three Object-Oriented Features of JAVA--Encapsulation, Inheritance, Polymorphism

Table of contents

1. Object-oriented and process-oriented

1. What is process-oriented?

2. What is object-oriented?

Second, the definition of the class

1. The concept of class:

2. The concept of the object:

3. The comparison between things and classes

4. Class definition format

 3. Basic features: encapsulation, inheritance, polymorphism super, this keyword abstract class interface

1. Packaging

(1) Basic concepts

(2) Four access control levels

(3) Package use

 2. Inheritance

2.1 Inherit parent class member variables/methods

2.2 Write parent class method

2.3 Overloading parent class methods

2.4 Features after inheritance - construction method

3. super and this

The parent class space takes precedence over the generation of child class objects

3.1 The meaning of super and this

3.2 Usage of super and this

4. Abstract class

 4.1 Overview

Origin:

definition:

4.2 Abstract usage format

4.3 Precautions

5. Interface

5.1 Overview

5.2 Define format

5.3 Basic implementation

5.4 Other member characteristics

 6. Polymorphism

6.1 Overview

6.2 The embodiment of polymorphism

6.3 Pros and Cons of Polymorphism

6.4 Reference type conversion

6.4.1 Why transformation


1. Object-oriented and process-oriented

Now more and more high-level languages ​​are becoming popular, such as the familiar c++, python, java, etc., which are all based on object-oriented languages.

And the most basic language that must be learned in school - C language is a process-oriented language.

1. What is process-oriented?

Process-oriented:

It is to analyze the steps needed to solve the problem, and then use functions to realize these steps step by step. When using them, they can be called one by one.

For example, how many steps does it take to apply for a certificate?

According to process-oriented thinking:

Step 1: Find someone to do the work

Step 2: Prepare materials for the work

Step 3: After completing the certificate, the certificate will be fed back to me

Here we can see that process-oriented is to realize one thing step by step

code representation

public void find(){}

public void handle(){}

public void feedback(){}

Just call these methods in turn

2. What is object-oriented?

In the Java language, everything is an object. Objects in the real world are abstractly reflected in the programming world, and an object represents a specific operation. Each object finally constitutes a complete program design, and these objects can exist independently or be inherited from other objects. Objects transfer information through interaction to realize program development.

An object is an abstraction of the things in question.

Object-oriented:

It is to abstract the things in reality into "objects". Each object is unique and can have its properties and behaviors. We can solve the problem by calling the methods and properties of these objects.

Use object-oriented thinking to solve the problem of putting elephants into refrigerators

A general understanding of the concept of an object can be said to be an abstract mapping of real things .

For example in this event:

Refrigerator as an object;

Elephant as an object.

The refrigerator has these functions: open the door, load objects, close the door

class fridge{     public void open(elephant){} //open the door     public void putIn(elephant){} //put in the refrigerator     public void close(elephant){} //close the door } class elephant{  public void eat() {} //eat }






Each object is independent and has its own functions, and only needs to realize its own functions. So when creating an object, only focus on what functions the object has, and don't consider how to implement these functions.

The benefits of object-oriented include good extensibility. For example, I have given an eating function to the elephant, and it can eat in the refrigerator by calling it. Object-oriented is to abstract real problems into objects, and solve problems by calling the properties or functions of each object.

If I want to modify my requirements and change the elephant to a puppy, do I have to change the elephant in each step to a puppy when I use process-oriented. And with object-oriented solutions, I can even recreate a puppy object, just select the puppy when calling. 

Second, the definition of the class

1. The concept of class :

Class (Class) is the basis of object-oriented programming (OOP, Object-Oriented Programming) to realize information encapsulation. A class is a user-defined reference data type, also known as a class type. Each class contains a description of the data and a set of functions for manipulating the data or passing messages. Instances of classes are called objects.

2. The concept of the object:

Java is an object-oriented programming language, and objects are the core of object-oriented programming. The so-called object is the entity in the real world, and there is a one-to-one correspondence between the object and the entity, that is to say, every entity in the real world is an object, which is a specific concept.

Objects have the following characteristics:

1. Objects have attributes and behaviors.

2. An object has a changing state.

3. The object is unique.

4. Objects are instances of a class.

5. Everything is an object, and all things in the real world can be regarded as objects.

A class is an abstraction of an object, and an object is the concreteness of a class.

3. The comparison between things and classes

A class of things in the real world:
Attributes: state information of things.      Behavior: What a thing can do.

The same is true for describing things with class in java:
member variables: attributes corresponding to things .   Member method: corresponds to the behavior of things.


4. Class definition format

public class ClassName{

         //Member variables

         //Member method

}

Define a class: It is to define the members of the class, including member variables and member methods .
Member variables: It is almost the same as defining variables before. It's just that the location has changed, in the class, outside the method .
Member method: It is almost the same as the previous definition method. Just remove the static.

Example of class definition format:

public class Student{

             //Member variables

             String name; //name

             int age; //age

}

 3. Basic features: encapsulation, inheritance, polymorphism super, this keyword abstract class interface

1. Packaging

(1) Basic concepts

The attributes and behaviors of a class of things are abstracted into a class, making its attributes private and its behavior public, improving the privacy of data and making the code modular. Doing so makes the code more reusable.

significance:

1. Put attributes and methods together as a whole, and then process them by instantiating objects;

2. Hiding the internal implementation details, you only need to interact with objects and their properties and methods;

3. Add access control to the attributes and methods of the class.

(2) Four access control levels

public: open to the public, with the highest access level

protected: Only exposed to classes or subclasses in the same package

Default: only exposed to classes in the same package

private: not open to the public, can only be accessed inside the object, with the lowest access level

(3) Package use

Hide as many things as possible to improve the concise interface

Add some attribute to allow external access, then provide a public method to access this attribute. If the dog class has a name and age attributes, the outside world is not allowed to directly access the attributes, but it is allowed to provide get and set methods to access.

public methods are public and can be accessed directly

public class Student {

    //成员变量 (属性)-----变量----储存数据的
    public String name;
    public String sex;
    public int age;
    public double height;
public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        student.name = "胡图图";
        student.sex = "男";
        student.age = 6;
        student.height = 1.11;
       student.introduce();

    }
}

The result of the operation is as follows: 

 Use the private method, which cannot be directly accessed by the outside, and requires getter and setter methods

**
 * 封装 :把属性私有化,实现了对外界的隐藏,然后通过共有的getter和setter方法对属性进行获取和赋值,保证了操作的安全性。
 * 一般属性私有化(private),方法公有化(public),除非方法只是用来内部调用,可以private修饰
 * 1.对属性使用private私有化进行修饰,实现了对外界的隐藏,外界不能够直接操作类的属性。
 * 2.定义针对属性的getter和setter方法,完成对属性的获放和设置值,在发放中可以完成完会验证。
 *
 * 注意:
 * 属性私有化后也可以通过有参数的构造方法进行赋值,且在有参构造方法中进行安全验证。
 */
public class Student {

    //成员变量 (属性)-----变量----储存数据的
    private String name;
    private String sex;
    private  int age;
    private  double height;

    /**
     * 构造方法:用来初始化对象(构造方法是用来创建对象的)
     * 语法:  访问修饰符 类名(参数列表..){}
     */
    //无参构造方法
    public Student(){
        System.out.println("无参的构造方法被调用!");
    }
    //有参构造方法:可以实现对类的属性进行赋值
    public Student(String name, String sex, int age, double height) {
        System.out.println("有参的构造方法被调用!");
        this.name = name;
        this.sex = sex;
        if(age>=0&&age<=100){
            this.age = age;
        }
        if (height>0){
            this.height = height;
        }
    }

    //getter setter
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    //toString:打印类的对象是打印的内存地址,重写了该方法,打印时就显示的是类的属性值列表
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", height=" + height +
                '}';
    }

    //成员方法(行为)----方法----完成---完成一些功能的---面向对象的体现
    public void introduce(){
        System.out.println("我是"+name+",性别"+sex+",今年"+age+"岁,身高:"+height);
    }
}
public class Test {
    public static void main(String[] args){
        //调用构造方法,实例化类的对象
        Student stu = new Student();
        stu.setName("张三");
        stu.setSex("男");
        stu.setAge(18);
        stu.setHeight(185.3);
        stu.introduce();
        System.out.println(stu);

        System.out.println("----------------------");
        Student stu1 = new Student("李四","男",29,217);
        stu1.introduce();
    }
}

 

 2. Inheritance

        Allows an object of one type to acquire the properties and methods of an object of another type. Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the methods from the parent class, so that the subclass has the same behavior as the parent class.

        The same attributes and methods in several classes are extracted and defined in the base class, and the subclasses no longer define these attributes and methods. After inheritance, it is equivalent to having these attributes and methods.

         1. The subclass inherits the parent class, and the public properties and methods defined by the parent class will be owned by the subclass, but the private properties and methods defined by the parent class cannot be inherited by the subclass. 

        2. The parent class inherits the method, and the subclass can be transformed to reimplement the function (method rewriting). When calling, the newly implemented method of the subclass is executed.

benefit:

1. Improve code reusability

2. There is a relationship between classes and classes, which is the premise of polymorphism

With the extends keyword, you can declare that a subclass inherits from another parent class

The definition format is as follows:

class subclass extends parent class{}

2.1 Inherit parent class member variables/methods

hanqishi继承了父类Dog

class Dog{

 public String name="小白";

  public void say(){

     System.out.println("汪汪汪");

   }

}

//哈奇士

class haqishi extends Dog {

    public void test(){

       System.out.println(name);

        say();

    }

Call the test() method of haqishi, and the test is as follows:

noob

woof woof

Test results: The subclass haqishi inherits the member variables and member methods of the parent class

The method inherited from the parent class can be transformed by the subclass to reimplement the function (method rewriting), and the newly implemented method of the subclass is executed when called.

2.2 Write parent class method

The subclass haqishi rewrites the say method of the parent class Dog
 

class Dog{

   public String name="小白";

    public void say(){

      System.out.println("汪汪汪");

    }

}

//哈奇士

class haqishi extends Dog {

    public void say() {

       //super.say();    继承父类原有方法

       System.out.println("哈哈哈");    }

}

Call the subclass say method, the test is as follows:

Hahaha

2.3 Overloading parent class methods

Overloaded methods must meet the following conditions:

1. The method name is the same

2. There is at least one difference in the parameter type, number, and order of the method

3. The return type of the method can be different

4. The modifiers of the method can be different
 

class Dog{

    public String name="小白";

    public void say(){

        System.out.println("汪汪汪");

    }

}

//哈奇士

class haqishi extends Dog {

   //重载 改变参数

    public void say(String name) {

       System.out.println(name+"汪汪汪");

    }

//重载 改变参数+返回值

    public int say(int age) {

        System.out.println("汪汪汪"+age);

        return age;

    }

call separately :/

haqishi h = new haqishi();

h.say();

h.say("Hatches");

h.say(6);

 The result is as follows:

woof woof

hutches woof woof

Wang Wang Wang 6

Precautions:

1. The subclass method overrides the parent class method, and must ensure that the permissions are greater than or equal to the parent class permission
2. The subclass method overrides the parent class method, and the return value type, function name, and parameter list must be exactly the same. 

2.4 Features after inheritance - construction method

2.4.1 Characteristics of inheritance

1. Java only supports single inheritance, not multiple inheritance.

2. Java supports multi-level inheritance (inheritance system).

2.4.2 Inherited constructors

1. The name of the constructor is consistent with the class name. So subclasses cannot inherit parent class constructors.

2. The role of the constructor is to initialize member variables. Therefore, in the initialization process of the subclass, the initialization action of the parent class must be executed first. There is a super() in the construction method of the subclass by default, which means calling the construction method of the parent class. After the member variables of the parent class are initialized, they can be used by the subclass.

code show as below:

class Fu {

        private int n;

        Fu(){

                System.out.println("Fu()";

        }

}

3. super and this

The parent class space takes precedence over the generation of child class objects

Every time a subclass object is created, the parent class space is initialized first, and then the subclass object itself is created. The purpose is that the subclass object contains its corresponding parent class space, so it can contain the components of its parent class. If the parent class members are not privately modified, the subclass can use the parent class members at will. When the code is reflected in the call of the constructor of the subclass, the constructor of the parent class must be called first. The understanding diagram is as follows:

3.1 The meaning of super and this

super : Represents the storage space identifier of the parent class (can be understood as a reference to the father).
this : Represents the reference of the current object (whoever calls it represents who).

3.2 Usage of super and this

1. Access members


this. member variable -------------- super. member variable of this class -----------
this. member method name of the parent class () ---- ----- Of this class

super. member method name () ------- parent class

 the difference:

1. Indicates that only assign values ​​​​to its own attributes, and the attribute values ​​​​of the parent class object are the default values

2. Indicates that the properties of the parent class have values, the properties unique to the subclass have values, and then the properties inherited from the parent class also have values

 

 The overall code is as follows:

//父类

public class Person {
    String name;
    int age;

    //类:变量和功能方法    有参无参构造方法 setter和getter方法  toString()
    public Person(){
        System.out.println("父类:Person构造方法被执行");
    }

    public void dy(){
        System.out.println("父类:dy方法被执行");
    }


}




//子类

public class Student extends Person{
String stuNum;


    public Student() {
        //super()表示调用父类的构造方法, 不写系统其实默认在子类的构造方法中调用了父类的构造方法,并且只能在第一行写
        super();
        System.out.println("Student类的构造方法执行");
    }

    public void fun(){
        this.stuNum = "1001";
        this.name="zy";
        this.age=19;
    }

    public void fun1(){
        this.stuNum = "1001";
        super.name="zy";
        super.age=19;
    }
    public void fun2(){
        super.name="xxx";
        super.age=111;
    }

    public void fun3(){
        System.out.println(super.name);
        System.out.println(super.age);
    }

    public void dy(){
        System.out.println("子类重写dy方法执行");
    }

    public void test(){
        this.dy();
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", stuNum='" + stuNum + '\'' +
                '}';
    }
}



//测试类

public class Test01 {
    public static void main(String[] args) {
    Student student = new Student();//调用无参的构造方法,实例化类的对象  默认先实例化它的父类对象
        System.out.println("------------------");
        student.fun2();
        student.fun();    //Student{name='zy', age=19, stuNum='1001'}

        student.fun();
        student.fun2();     //Student{name='xxx', age=111, stuNum='1001'}

        student.fun3();

        System.out.println(student);


        Student s2 = new Student();
        System.out.println("----------");
        s2.test();

    }
}

operation result: 

 

4. Abstract class

 4.1 Overview

Origin:

The methods in the parent class are overridden by its subclasses, and the implementations of the subclasses are different. Then the method declaration and method body of the parent class, only the declaration still has meaning, but the method body has no meaning. We call a method without a method body an abstract method. Java grammar stipulates that a class containing abstract methods is an abstract class.

definition:

Abstract method : A method without a method body.

Abstract class : A class that contains abstract methods.

4.2 Abstract usage format

abstract method

Use the abstract keyword to modify the method, and the method becomes an abstract method. The abstract method only contains a method name, but no method body.

/**
 * 抽象类:使用abstract关键字进行修饰的类叫做抽象类
 *          1.抽象类里面不是必须由抽象方法
 *          2.一个类里面有抽象方法,这个类必须满足抽象类
 */

//父类

public abstract class Person {
    String name;
    int age;

/**
 * 抽象方法:
 *  1.方法只有声明没有方法体:  声明即规定方法三要素: 方法名、参数列表、返回值类型
 *  2.要使用abstract关键字进行修饰
 *
 *  定义抽象方法的意义:
 *          1.能够对子类进行约束:子类必须实现父类的抽象方法,或者子类声明为抽象类
 *          2.抽象类通过定义抽象方法实现了一种规范,要求它的子类必须具备某种功能,具体如何实现以子类的具体实现为准
 */
public  void study(){

}
}


//子类

public class Student extends Person{
    String stuNo;

    public void study(){
        System.out.println("Student子类重写study方法执行");
    }
}


//子类

public class Teacher extends Person{
    String tid;

}

Anonymous inner class: 

public class test1 {
    public static void main(String[] args) {
        //匿名内部类
        Person p = new Person() {
            @Override
            public void study() {
                //实现抽象方法
            }
        };
        Student student = new Student();
    }
}

4.3 Precautions

Regarding the use of abstract classes, the following are the details to pay attention to in terms of grammar. Although there are many entries, if you understand the essence of abstraction, you don't need to memorize it by rote.
1. An abstract class cannot create an object. If it is created, the compilation will fail and an error will be reported. Only objects of its non-abstract subclasses can be created.
        Understanding: Assuming that an object of an abstract class is created and an abstract method is called, and the abstract method has no specific method body, it is meaningless.

2. In an abstract class, there can be a construction method, which is used for initializing the members of the parent class when the subclass creates an object.
        Understanding: In the construction method of the subclass, there is a default super(), which needs to access the construction method of the parent class.

3. Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.
        Understanding: The purpose of an abstract class that does not contain an abstract method is to prevent the caller from creating an object of this class, which is usually used for some special class structure design.

4. The subclass of the abstract class must rewrite all the abstract methods in the abstract parent class, otherwise, the compilation will fail and an error will be reported. Unless the subclass is also an abstract class.
        Understanding: Assuming that all abstract methods are not rewritten, a class may contain abstract methods. Then after the object is created, it is meaningless to call the abstract method.

5. Interface

5.1 Overview

An interface is a reference type in the Java language, and it is a collection of methods. If the inside of a class encapsulates member variables, construction methods, and member methods, then the inside of an interface mainly encapsulates methods, including abstract methods (DK 7 and before , default and static methods (DK 8), private methods (DK 9).

The definition of an interface is similar to defining a class, but using the interface keyword. It will also be compiled into a cass file, but it must be clear that it is not a class, but another reference data type.

Reference data types: arrays, classes, interfaces.

The use of interfaces, it cannot create objects, but can be implemented ( implements , similar to being inherited). A class that implements an interface (which can be regarded as a subclass of the interface) needs to implement all the abstract methods in the interface, create an object of this class, and then call the method, otherwise it must be an abstract class.

5.2 Define format

public interface interface name {                 // abstract method                 // default method                 // static method                 // private method



}

Contains abstract methods

Abstract method: use the abstract keyword to modify, can be omitted, and there is no method body. This method is intended for use by subclass implementations.
code show as below:

public interface InterFaceName {
        public abstract void method(); 

}

Contains default methods and static methods

Default method: use default modification, cannot be omitted, for subclasses to call or subclasses to override.

Static method: Use static modification for direct calling by the interface.

code show as below:

public interface InterFaceName { public default yoid method() {                 // execute statement

        }
public static void method2() {                 //execute statement

        }

}

Contains private methods and private static methods

Private method: Use private modification for default method or static method call in the interface.
The code is as follows:

public interface InterFaceName { private void method() {                 //execution statement 

        }

}

5.3 Basic implementation

Implementation overview

The relationship between a class and an interface is an implementation relationship, that is, a class implements an interface, and the class can be called the implementation class of the interface, or a subclass of the interface. The action of implementation is similar to inheritance, and the format is similar, but the keywords are different, and the implements keyword is used for implementation.

    Non-abstract subclasses implement interfaces:
        1. All abstract methods in the interface must be rewritten.
        2. Inherit the default method of the interface, which can be called directly or rewritten.

Implementation format:

class class name implements interface name{         //rewrite the abstract method in the interface [required]         //rewrite the default method in the interface [optional]

}

Use of static methods

Static is related to the .class file, and can only be called by the interface name, not by the class name of the implementation class or the object of the implementation class

Use of private methods

        Private method: Only the default method can be called.
        Private static methods: Default methods and static methods can be called.
If there are multiple default methods in an interface, and there are repeated content in the method, then they can be extracted and encapsulated into a private method for the default method to call. From a design point of view, the private method is for the default method and the static method. method aids. Students can test themselves on the basis of the skills they have learned.

5.4 Other member characteristics

In the interface, member variables cannot be defined, but constants can be defined, and their values ​​cannot be changed. By default, they are decorated with public static final.

In an interface, there is no constructor, and objects cannot be created.

In the interface, there is no static code block.

The overall code is as follows:

/**
 * 接口的定义使用interface关键字
 *  1.接口不能有成员变量
 *  2.接口中一般定义的是抽象方法,JDK8开始可以定义默认方法和静态方法,JDK9可以定义私有方法
 *  3.通过定义接口,就相当于定义一种规范或者约束,实现该接口的子类必须重写接口中定义的抽象方法,或者子类定义为抽象类
 *
 *  在程序开发中,一般定义接口用来规定完成模块操作的各个处理方法,具体的功能实现根据不同的需求定义不同的实现类来完成功能
 */

//父类

public interface USB {
    //只能定义方法。
    //抽象方法
    void read();
    void write();

    //默认方法-------JDK8    子类会被继承
    public default void run(){
        System.out.println("启动");
    }

    //静态方法-------JDK8  不会被继承,子类也无法调用
    public static void fun(){

    }

    //私有方法-------JDK9    子类不会被继承
//    private void fun1(){
//
//    }
}


//子类

public class Kingston implements USB{

    @Override
    public void read() {
        System.out.println("Kingston执行读操作");
    }

    @Override
    public void write() {
        System.out.println("Kingston执行写操作");
    }
}



//子类

public  class SanDisk implements USB{
    @Override
    public void read() {
        System.out.println("SanDisk执行读操作");
    }

    @Override
    public void write() {
        System.out.println("SanDisk执行写操作");
    }
}

 6. Polymorphism

6.1 Overview

Polymorphism is the third major feature of object-oriented after encapsulation and inheritance.

Polymorphism occurs in inheritance or implementation relationships .

In life, such as running movements, kittens, puppies and elephants run differently. Another example is the movement of flying. Insects, birds and airplanes fly differently. It can be seen that the same behavior can be manifested in different forms through different things. Polymorphism describes such a state.

Definition
        Polymorphism : Refers to the same behavior with multiple different manifestations.

premise [emphasis]

1. Inheritance or implementation [choose one of the two]
2. Method rewriting [meaning embodiment: no rewriting, meaningless]
3. Parent class reference points to subclass object [format embodiment]

6.2 The embodiment of polymorphism

The format of the polymorphic embodiment:

Parent class type variable name = new subclass object;
variable name. method name();

Parent class type: Refers to the parent class type inherited by the subclass object, or the parent interface type implemented.

code show as below:

Fu f = new Zi();
f.method();

When calling a method in a polymorphic way, first check whether the method exists in the parent class, if not, a compilation error occurs; if so, the subclass overridden method is executed.

6.3 Pros and Cons of Polymorphism

We already know that the polymorphic compilation stage looks at the type of the parent class on the left. If the subclass has some unique functions, then the polymorphic writing method cannot access the unique functions of the subclass.

In the actual development process, the parent class type is used as the formal parameter of the method, and the subclass object is passed to the method to call the method, which can better reflect the scalability and convenience of polymorphism.

6.4 Reference type conversion

6.4.1 Why transformation

The polymorphic way of writing cannot access the unique functions of subclasses.

When calling a method in a polymorphic way, first check whether the method exists in the parent class, if not, a compilation error occurs. That is to say, you cannot call methods owned by subclasses but not in superclasses. Compilation is wrong, let alone run. This is also a little "little trouble" that polymorphism brings us. Therefore, if you want to call a subclass-specific method, you must do downcasting.

Polymorphic transformation is divided into two types: upward transformation and downward transformation:

Upcasting (automatic transition)

       Upcasting: Polymorphism itself is the process of upcasting from a subclass type to a parent class type, and this process is the default. Upcasting occurs when a parent class reference points to a subclass object.

Use format:

Parent class type variable name = new subclass type ();
such as: Animal a = new cat ();

The reason is: the parent class type is a large-scale type relative to the child class, and Animal is an animal class and a parent class type. Cat is a cat class, which is a subclass type. The scope of the Animal type is of course very large, including all animals. Therefore, if the scope of the subclass is small, it can be directly and automatically transformed to the variable of the parent class type.

downcasting (mandatory conversion)

      Downcasting: The process of downcasting from the parent class type to the subclass type, this process is mandatory. For a subclass object that has been upwardly transformed, the parent class reference can be converted into a subclass reference, and the forced type conversion format can be used, which is downcasting.

Subclass variable name = (subclass type) parent class variable name;
such as: Animal a = new cat();

        Cat c =(Cat) a; 

Overall code:

/**
 * 多态:是指同一行为,具有多个不同表现形式。(调用同样的方法,执行的是不同的功能)
 * 1. 发生在有继承或者实现接口的情况下
 * 2. 在子类中对方法进行了重写
 * 3.父类引用指向子类对象    父类类型 变量名=new 子类对象()
 *
 *  多态的好处: 在开发中可以把父类(接口类型)类型定义为方法的形参,在实际调用的时候传入的实际参数就比较灵活了,
 *              可以传入父类类型的对象,也可以传入任意一个子类类型的对象。
 *
 *  多态本质就是子类对象向上转型为父类的引用(子类对象赋值给父类变量),;
 */

//测试类

public class Test02 {
    public static void main(String[] args) {
//        Animal a1 = new Cat();
//        Animal a2 = new Dog();
//        a1.call();
//        a2.call();

        System.out.println("---------------------------");
        //调用类里面的方法:静态方法--直接类名.方法名;   非静态方法--实例化对象,然后对象名.方法名;
//        AnimalAction ac = new AnimalAction();
//        //如果没有父类变量 = 子类对象的这种技术存在
//        //多态在方法调用中的应用体现
//        Animal a1 = new Animal();
//        Animal a2 = new Cat();
//        Animal a3 = new Dog();
//        ac.action(a1);

        Cat c1 = new Cat();
        Animal a= new Cat();
        a.call();
        Cat c = (Cat) new Animal();
        c.sleep();
    }
}


//子类

public class Cat extends Animal{
    public void call(){
        System.out.println("喵喵叫");
    }
    public void sleep(){
        System.out.println("猫在睡觉...");
    }
}


//子类

public class Dog extends Animal{
    public void call(){
        System.out.println("汪汪叫");
    }
}


//父类

public class Animal {
    public void call(){
        System.out.println("动物在叫");
    }
}



public class AnimalAction {
    /**
     * 给方法一个Animal类型的对象(变量),然后调用call()方法
     * @param animal
     */
    public void action(Animal animal){
        animal.call();
    }
}

Guess you like

Origin blog.csdn.net/weixin_67224308/article/details/127851132