学习笔记---对象类型的转换

对象类型的转换

1. 注意点:

  • 父类为高级,子类为低级
  • 从高级转到低级需要强制转换,从低级转到高级则自动转换
  • 子类转为父类时,可能丢失一些自己的方法
  • 方便方法的调用,减少代码的重复,做到简洁

2. 格式:

  • ((子类)对象名).xxx方法

代码示例:

package oop.Demo05;

public class Student extends Person{
    
    
    @Override
    public void run() {
    
    
        System.out.println("son");
    }

    public void eat(){
    
    
        System.out.println("eat");
    }
}
package oop.Demo05;

public class Person {
    
    
    public void run(){
    
    
        System.out.println("run");
    }
}
package oop;

import oop.Demo05.Person;
import oop.Demo05.Student;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        //类型之间的转化     父(高)         子(低)
        //从高转到低需要强制转换  从低到高则自动转换
        Person person = new Student();
        Student student = new Student();

        //person.eat();     报错
        ((Student)person).eat();    //eat

        //子类转换为父类时,可能丢失一些自己的方法
        Person person1 = student;
        //person1.eat();    报错
        ((Student)person1).eat();   //eat
    }
}

猜你喜欢

转载自blog.csdn.net/yang862819503/article/details/113733346