Home  >  Article  >  Java  >  What are the uses and principles of Java polymorphism and abstract classes

What are the uses and principles of Java polymorphism and abstract classes

王林
王林forward
2023-04-28 21:01:05944browse

We know the three major features of Java: encapsulation, inheritance, and polymorphism. The first two have been mentioned before in Introduction to Java (6). Now let’s talk about the feature of polymorphism.

What is polymorphism?

Polymorphism, as the name suggests, means multiple forms

The meaning of polymorphism in Java:

  • Send a message to an object, let this The object decides on its own which behavior to adopt in response to this message

  • The reference of the subclass object is assigned to the parent class reference variable to implement dynamic method calling

Prerequisites for polymorphism in Java:

  • Inheritance

  • Overriding of parent class methods

  • Upward Transformation

My explanation of polymorphism:

For example, we are humans, students, and young people. I can do things as humans. , you can also use your identity as a student to buy student tickets, or you can use your identity as a young person to do charity, so that we can do different things in different forms. Is this better understood?

Note:

Polymorphism prerequisite: there must be a child-parent class relationship.

When calling a method using a polymorphic parent class reference variable, the overridden method of the subclass will be called.

The definition and usage format of polymorphism:

Parent class type variable name = new subclass type ();

Characteristics of members in polymorphism:

  • Polymorphic member variables: Look at the left when compiling and running

  • Polymorphic member methods: Look at the left when compiling and right when running

Polymorphic transformation:

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

  • Upward transformation: multiple The state itself is a process of upward transformation

  • Usage format: parent class type variable name=new subclass type();

  • Applicable scenarios : When there is no need to face subclass types, the corresponding operations can be completed by improving extensibility or using the functions of the parent class.

  • Downward transformation: A subclass object that has been upwardly transformed can use the format of forced type conversion to convert the parent class reference type into the subclass reference type

  • Usage format: subclass type variable name = (subclass type) parent class type variable;

  • Applicable scenarios: When you want to use the unique functions of the subclass.

Code explanation:

public class Person {     //人类,作为父类使用
    public void speak(){
        System.out.println("我们都是一个人");
    }
}



public class Student extends Person{    //继承父类,相当于我们是学生,有人的方法
    @Override
    public void speak(){
        System.out.println("我是人类中的学生");
    }
}



public class Child extends Person{   //继承父类,相当于我们是孩子,有孩子的行为
    @Override
    public void speak(){

        System.out.println("我是人类中的孩子");
    }
}




//测试类
public class TestMain {
    public static void main(String[] args) {

		//父类类型 变量名=new 子类类型();
        Person p = new Student();   //子类对象的引用赋值给父类 
        p.speak(); //多态 相当于这里使用的是Student的方法。输出我是人类中的学生
        //我作为人,我用学生的身份,说出:我是人类中的学生


		Person p = new Child(); 
		p.speak();  //输出:我是人类中的孩子
		//我作为人,用孩子的身份,说出我是人类中的孩子

    }
}

//这段代码,我们用到了 继承,重写,向上转型,因为多态本来就是向上转型的过程

The role of polymorphism:

After introducing polymorphism, what is the use of polymorphism? Why polymorphism can be regarded as the three major features of Java. There must be a reason:

  • Improve the reusability of the code

  • Reduce the coupling between modules

Here I would like to introduce to you what is the polymorphic mechanism? How does the Java language implement polymorphism? (It may be a bit difficult to understand, and I don’t fully understand the content, but this is also an interview question)

The so-called polymorphism refers to the specific type pointed to by the reference variable defined in the program and the specific type pointed by the reference. The method call issued by a variable is not determined during programming, but is determined during the running of the program. That is, which class instance object a reference variable will point to, and the method call issued by the reference variable is a method implemented in which class. , must be determined during program execution. Because the specific class is determined only when the program is running, the reference variable can be bound to various class implementations without modifying the source program code, causing the specific method called by the reference to change accordingly, that is, it does not need to be modified. The program code can change the specific code bound to the program when it is running, allowing the program to select multiple running states. This is polymorphism. Polymorphism is divided into compile-time polymorphism and run-time polymorphism. Among them, editing-time polymorphism is static and mainly refers to method overloading. It distinguishes different functions based on different parameter lists. After editing, it will become two different functions. There is no polymorphism at runtime. . Runtime polymorphism is dynamic, and it is achieved through dynamic binding, which is what we call polymorphism.

For understanding of polymorphism, you can also refer to a piece of code:

class People{     //父类
    public void eat(){
        System.out.println("我们会吃饭");
    }
}


class Student extends People{  //继承父类
    @Override
    public void eat(){
        System.out.println("我会吃肉");
    }
    public void study(){
        System.out.println("我们要好好学习");
    }
}


class Teacher extends People{     //继承父类
    @Override
    public void eat(){
        System.out.println("老师会吃蔬菜");
    }
    public void teach(){
        System.out.println("老师要认真上课");
    }
}

//测试类:
public class TestMain {
    public static void main(String[] args) {
        People p=new Stu();      //子类对象的引用赋值给父类 
        p.eat();       //输出: 我会吃肉
    }
}

Abstract class:

What is an abstract class?

A common class is a complete functional class that can directly generate instantiated objects, and can include constructors, common methods, static methods, constants, variables, etc. in a common class. Abstract classes refer to components that add abstract methods to the structure of ordinary classes.

Abstract method:

There will be a "{}" above all ordinary methods, which represents the method body. Methods with method bodies must be used directly by the object. Abstract methods refer to methods without a method body, and abstract methods must also be modified with the keyword abstract. In other words, the abstract method in the abstract class does not need to be written, and then rewritten after it is inherited.

Abstract class declaration keyword: abstracat

Define an abstract class:

public abstract class studnet{//定义一个抽象类
	
	public void study(){                         //普通方法
		System.out.println("我会学习");
	}
	
	public abstract void eat();         //抽象方法,没有方法体,有abstract关键字做修饰
	
}

//注意: 有抽象方法,这个类必须是抽象的!!!

Example explanation:

The shape class Shape needs to be provided for calculating area and sum Perimeter method, but the shape itself has not been determined, then the method of calculating perimeter and area cannot be determined. At this time, we need to use abstract classes and abstract methods.

由于Shape类计算周长和面积的方法无法确定,那么就可以将这样的方法声明为抽象的,以便在具体的子类中进行实现。

//定义一个shape类,但是没有具体的形状,所以我们定义成抽象类
public abstract class Shape {
    
    private int a;
    public abstract void area(){}     //求面积的方法
    public abstract void perimeter();   //求周长的方法

    public Shape() {    //无参构造
    }

    public Shape(int a) {
        this.a = a;
    }
}
//计算圆形面积的子类

public  abstract class shape {    //有抽象方法的类,则一定是抽象类,需要关键字abstract修饰

        private int a;
        public abstract void area();     //求面积的方法,没有方法体的方法,需要关键字abstract修饰
        public abstract void perimeter();   //求周长的方法
}


//创建计算圆面积和周长的子类,并继承抽象类shape,并重写shape内的方法
public class Circle extends shape{

    public static double pi = 3.14;
    private double r;  //半径


    @Override
    public void area() {
        System.out.println("圆的面积:"+Circle.pi*this.r*this.r);
    }

    @Override
    public void perimeter() {
        System.out.println("圆的周长为:"+2*Circle.pi*this.r);
    }

    public Circle() {
    }

    public Circle(double r) {  //
        this.r = r;
    }

}


//测试类:
public class TestMain {
    public static void main(String[] args) {
        Circle c = new Circle(5);        //传入半径为:5
        c.area();
        c.perimeter();

    }

}

//输出结果: 圆的面积:78.5
// 圆的周长为:31.400000000000002

抽象方法和抽象类的注意事项:

  • 抽象类中是可以有构造函数的,并且构造函数的写法和其它类没有区别,只不过它真正跑起来是因为子类构造函数的super调用,毕竟我们没办法new一个抽象类对象出来,只能把抽象类的构造函数交给子类的构造函数去使用。

  • 抽象类中不一定包含抽象方法,但是有抽象方法的类一定是抽象类。

  • 抽象类的子类,必须重写父类中所有的抽象方法,如果有一个抽象方法没有重写,都会出现编译错误不给过,这时也可以把子类也声明为抽象类,报错就会消失。

The above is the detailed content of What are the uses and principles of Java polymorphism and abstract classes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete