Home  >  Article  >  Java  >  What are state and abstract classes in Java?

What are state and abstract classes in Java?

王林
王林forward
2023-05-26 14:22:461510browse

Polymorphism:

We know the three major features of Java: Encapsulation, inheritance, 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 is Multiple formsmeans

The meaning of polymorphism in Java:

1. Send a message to an object and let the object decide which behavior to adopt in response to the message

2. Assign the reference of the subclass object to the parent class reference variable to implement dynamic method calls

Prerequisites for polymorphism in Java:

1. Inheritance

2. Overriding of parent class methods

3. Upward transformation

My explanation of polymorphism:

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

Note:

Polymorphic prerequisites: 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 ();

Polymorphism Characteristics of members:

  • Polymorphic member variables: Compile and run, look on the left

  • Polymorphic member methods: Compile and run, look on the left. Run and look at the right side

Polymorphic transformation:

  • Polymorphic transformation is divided into upward transformation and downward transformation Two types of

  • Upward transformation: Polymorphism 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 scalability 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. . Polymorphism is achieved through dynamic binding, so runtime polymorphism is dynamic.

For the 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:

All ordinary methods with a method body will be used directly by the object, because they will have a "{}" to represent the method body. Abstract methods refer to methods that do not have implementation code and must be modified with the abstract keyword. To put it another way, abstract methods in abstract classes can be overridden by inheritors in subsequent implementations, and do not necessarily need to be implemented in the abstract class.

Abstract class declaration keyword: abstracat

Define an abstract class:

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

举例解释:形状类Shape需要提供用于计算面积和周长的方法,但是形状本身没有被确定,那么计算周长和面积的方法就无法确定,此时我们就需要使用抽象类和抽象方法。

由于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一个抽象类对象出来,只能把抽象类的构造函数交给子类的构造函数去使用。

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

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

简洁总结:

  • 抽象方法:没有方法体的方法,需要关键字abstract修饰

  • 有抽象方法的类,则一定是抽象类,需要关键字abstract修饰

  • 抽象方法不能使用private和static修饰

  • 抽象类,不一定有抽象方法的类

  • 抽象类,不一定有抽象方法的类

  • 抽象类可以有构造函数

普通类和抽象类有哪些区别?

  • 普通类不能包含抽象方法,抽象类可以包含抽象方法

  • 抽象类不能直接实例化,普通类可以直接实例化。

The above is the detailed content of What are state and abstract classes in Java?. 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