重写
前提是继承关系,子类重写父类的方法
- 方法名必须相同
- 参数列表必须相同
- 修饰符:范围可以扩大 public > protected > default > private
- 抛出的异常:范围可被缩小,不能扩大
- 重写子类的方法必须和父类的方法要一致,方法体不同
- 快捷方式:Alt+insert+override
public class Person {
public void run(){
System.out.println("run");
}
}
public class Student extends Person{
@Override
public void run() {
System.out.println("son run");
}
public void eat(){
System.out.println("son eat");
}
}
main中test代码:
public static void main(String[] args) {
//一个对象的实际类型是确定的
//new Student();
//new Person();
//可以指向的引用类型就不确定了:父类的引用类型指向子类
//Student能调用的方法都是自己或者继承父类的
Student s1 = new Student();
//Person 父类型,可以指向子类,但不能调用子类独有的方法
Person s2 = new Student();
Object s3 = new Student();
//对象能执行哪些方法,主要看对象左边的类型和右边关系不大
s1.run();
s2.run(); //子类重写了父类的方法,执行子类的方法
s1.eat();
// s2.eat(); 子类独有方法,父类不可调用
}
结果:son run 子类
son run 子类重写父类
son eat 子类私有方法,父类不能调用
多态
方法的多态,属性没有多态
- 继承关系
- 方法需要重写
- 父类引用指向子类对象
Father f1 = new Son( );
以下不可重写
- static 静态方法,属于类,不属于实例
- final 常量
- private 私有
子类 Student s1 = new Student();
父类引用指向子类的类型
Person s2 = new Student();
Object s3 = new Student();
instanceof 和类型转换
- instanceof 判断一个对象是什么类型
X instanceof Y 根据x,y是否是父子关系,来判断编译能否通过
public static void main(String[] args) {
//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object obj = new Student();
System.out.println(obj instanceof Student); //true
System.out.println(obj instanceof Person); //true
System.out.println(obj instanceof Object); //true
System.out.println(obj instanceof Teacher); //false
System.out.println(obj instanceof String); //false
System.out.println("==========================");
Person per = new Student();
System.out.println(per instanceof Student); //true
System.out.println(per instanceof Person); //true
System.out.println(per instanceof Object); //true
System.out.println(per instanceof Teacher); //false
//System.out.println(per instanceof String); 编译出错
System.out.println("==========================");
Student stu = new Student();
System.out.println(stu instanceof Student); //true
System.out.println(stu instanceof Person); //true
System.out.println(stu instanceof Object); //true
//System.out.println(stu instanceof Teacher); 编译出错
//System.out.println(stu instanceof String); 编译出错
}
- 类型转换
父类子类之间转换
父------子:
Person per = new Student( );
((Student)per).go( ); 父类转换成子类后调用Student中的方法
子-------父:
Student stu = new Student( );
stu.go( );
Person per = stu;
- 父类引用指向子类对象
- 子类转换父类(向上转换) 可以直接转
父类转换子类(向下转换) 强制转换- 方法调用便利,减少重复代码,简洁