Java多态笔记(多态的实现方式)

    多态指的就是在同一个方法中,由于参数类型不同而导致的执行效果不同的现象就是多态。说直白一点就是不同对象执行同一个方法会得到不同的结果。
    实现多态的条件:

  • 要有继承
  • 要有重写
  • 父类引用指向子类对象
    实例:
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //创建YellowPerson类的实例,是父类的变量引用
        Person yellowPerson = new YellowPerson();
        //创建YellowPerson类的实例,是父类的变量引用
        Person blackPerson = new BlackPerson();
        AA(yellowPerson);
        AA(blackPerson);
    }
    //创建一个静态方法接收Person类型的变量
    public static void AA(Person person) {
    
    
        person.eat();
        person.run();
    }
}
//父类Person
class Person{
    
    
    int height;
    String color;
    //人吃饭的方法
    public void eat(){
    
    
        System.out.println("中国人使用筷子吃饭....");
    }
    //人跑的方法
    public void run(){
    
    
        System.out.println("中国人跑步真厉害....");
    }
}
//YellowPersonS继承父类Person
class YellowPerson extends Person{
    
    
    int height;
    String color;
    //子类重写吃饭的方法
    public void eat(){
    
    
        System.out.println("黄种人在吃饭....");
    }
    //子类重写人跑的方法
    public void run(){
    
    
        System.out.println("黄种人在跑步....");
    }
}
//BlackPerson继承父类Person
class BlackPerson extends Person{
    
    
    int height;
    String color;
    //子类重写吃饭的方法
    public void eat(){
    
    
        System.out.println("黑种人在吃饭....");
    }
    //子类重写人跑的方法
    public void run(){
    
    
        System.out.println("黑种人在跑步....");
    }
}

运行结果:
在这里插入图片描述
    Java中除了static方法和final方法(private方法属于final方法)是前期绑定,其他所有方法都是后期绑定。

  • final关键字修饰的方法不能被重写,即防止被其他人覆盖该方法,同时也能避免动态绑定。
  • private关键字修饰的方法对子类不可见,也就不能被子类继承,那么也就无法通过子类对象调用private级别的方法;唯一调用的途径就是在类内通过其对象本身。所以说,private级别的方法和定义这个方法的类绑定在一起了。
  • static关键字修饰的方法属于类而非对象,所以不能被重写,但static方法可以被子类继承(不能表现出多态性,因为父类的静态方法会被子类覆盖)。

猜你喜欢

转载自blog.csdn.net/qq_42494654/article/details/109322246