多态形式类型转换

package d3_polymorphic_convert;
//定义一个父类(人类类)
public class People {
    public void eat(){
        System.out.println("正在吃饭~~~");
    }
}
package d3_polymorphic_convert;
//定义一个老师类继承人类类
public class Teacher extends People{
    @Override
    public void eat() {//继承父类的方法
        System.out.println("老师正在吃饭~~");
    }

    public void teaching(){//老师类独有的教学方法
        System.out.println("老师在教学生知识~~");
    }
}
package d3_polymorphic_convert;
//定义一个学生类继承人类类
public class Student extends People{
    @Override
    public void eat() {//继承父类的方法
        System.out.println("学生正在吃饭~~~");
    }

    public void learn(){//学生类独有的方法
        System.out.println("学生正在学习~~~");
    }
}
package d3_polymorphic_convert;

public class Test {

    public static void main(String[] args) {
        //自动类型的转换
        People p = new Teacher();
        p.eat();

        System.out.println("--------------");
        //强制类型的转换
        People p2 = new Student();
        p2.eat();
        Student s = (Student) p2;
        s.learn();
        //Teacher t = (Teacher) p2;//强制转换编译不会报错(运行会报错)

        System.out.println("--------------");
        ifpeople(new Teacher());
        ifpeople(new Student());
    }
    //强制类型转换(判断调用的是哪个类)//在不知道调用哪个类的时候可以使用
    public static void ifpeople(People p1){
        if (p1 instanceof Teacher){
            Teacher t = (Teacher) p1;
            t.teaching();
        }else if (p1 instanceof  Student){
            Student s1 = new Student();
            s1.learn();
        }
    }

}

你可能感兴趣的:(java)