java三大特性——多态

自我理解

1,对象执行那些方法,主要看对象左边的类型,和右边的关系不大
2,子类重写了父类的方法,执行子类的方法
3,Student能调用的方法都是自己的或者继承父类的
4,Person父类型,可以指向子类,但不能调用子类的方法

多态注意事项:
1,多态是方法的多态,属性没有多态
2,父类和子类 有联系
3,存在继承关系,方法需要重写,父类引用指向子类对象
father f1=new Son();
Student a1= new Student();
调用子类的方法
Person s2 =new Student();
当调用方法时调用的是父类的方法,要是子类重写了父类的方法则调用子类的方法

4,不能重写的方法(不能重写,无多态)
static 静态方法属于类,不属于实例
final 常量
private 私有方法

//父类方法
    public void run(){
        System.out.println("zou");
    }
    //子类方法
    public void run(){
        System.out.println("son");
    }
    //Main方法
     Student s1=  new Student();
    Person s2 =new Student();
    s2.run();
    s1.run();
    //结果
    son son

一,instanceof(判断是否能强制转化)
x instanceof y 能不能编译通过(x所指的实际类型是不是y的子类型)
左边是对象右边是类,当对象是右边类或其子类的对象是就是true否则就是false
1,如果x与y没有父子关系就不可编译
2,x是一个名字,下指向的对象如果是后面y的子类那么为true

二,多态,父类引用指向子类的对象
1,子类转换为父类(向上转换可以直接转化)
2,把父类转化成子类需要强制转换(可能会丢失内容)
3,方便方法的调用,减少重复的代码

 Object object = new Student();
        System.out.println(object instanceof Student);
        System.out.println(object instanceof  Person);
        System.out.println(object instanceof String);
        System.out.println(object instanceof Object);
        System.out.println(object instanceof Teacher);
        System.out.println("=================");
        Person person=new Student();
        System.out.println(person instanceof Student);
        System.out.println(person instanceof  Person);
        System.out.println(person instanceof Object);
        System.out.println(person instanceof Teacher);

        Student student=new Student();
        System.out.println(student instanceof Student);
        System.out.println(student instanceof  Person);
        System.out.println(student instanceof Object);

        /*结果:
true
true
false
true
false
=================
true
true
true
false

true
true
true
*/
//强制转化
   //子类转换为父类可能会丢失自己本来的方法
        Person person1=new Student();

        Person obj=new Student();
//格式一
        Student student1=(Student)obj;
        student1.go();
//格式二
        ((Student)obj).go();


版权声明:本文为yfq_29原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。