Java,类的继承与多态

继承与多态

多态

父类:Person

  • 父类有一个 run() 方法
public class Person {
    
    
    public void run()
    {
    
    
        System.out.println("father run");
   	}
}

子类:Student 继承父类Person

  • 有一个重写父类的 run() 方法
  • 还有子类自己的 eat() 方法
public class Student extends Person{
    
    
    public void run()
    {
    
    
        System.out.println("son run");
    }

    public void eat()
    {
    
    
        System.out.println("son eat");
    }
}

创建 s1,s2,s3三个对象

  • s1 : Student类对象
  • s2 : Person类型引用 Student类对象
  • s3 : Person类对象
Student s1=new Student();
Person s2=new Student();
Person s3=new Person();

调用方法

  • s1调用子类Student重写的的 run() 方法
  • s1调用子类Student自己定义的 eat() 方法
s1.run();//子类重写方法
s1.eat();//子类自己定义的方法
s2.run();//子类重写方法
s2.eat();//Error!!
  • s2也调用子类Student重写的的 run() 方法,因为s2是声明为Person类型,但是引用了子类Student对象 【new Student()】,所以可以调用子类重写的方法
  • s2无法调用子类自己定义的 eat() 方法,因为s2声明为Person类型

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hhb442/article/details/108074411