方法的重写
重写
-
需要有继承关系,子类重写父类的方法
- 方法名必须相同
- 参数列表必须相同
- 修饰符:范围可以扩大 public>proteceted>default>private
- 抛出的异常:范围可以被缩小,但不能扩大:ClassNotFoundException – >Exception
-
重写,子类的方法和父类必须一致,方法体可以不同!
-
为什么要重写
- 父类的功能,子类不一定需要,或者不满足
- 快捷键Alt + Insert : override
-
静态方法不会重写,只与左边类型有关。
-
代码
import oop.day15.A; import oop.day15.B; public class Appliday15 { //静态的方法和非静态的方法区别很大! //静态方法:方法的调用只和左边,定义的数据类型有关 //非静态:重写 public static void main(String[] args) { A a = new A(); a.test();//A //父类的引用指向了子类 B b = new A();//子类重写了父类的方法 b.test(); } }
public class A extends B{
public void test(){
System.out.println("A=>test()");
}
}
public class B {
public void test(){
System.out.println("B=>test()");
}
}
多态
- 代码
程序体
import oop.day16.Person;
import oop.day16.student;
public class Appliday16 {
public static void main(String[] args) {
//一个对象的实际类型是确定的
//可以只想的应用类型就不确定了:父类的引用指向子类
//Student能调用的方法都是自己的或者继承父类的。
student S1 = new student();
//Person 父类型,可以指向子类,但是不能调用子类的方法
Person S2 = new student();
Object S3 =new student();
//对象能执行哪些方法,主要看对象左边的类型,和右边关系不大
S2.eat();//子类重写了父类的方法,父类需存在此方法
S1.eat();
}
}
父类Person
public class Person {
public void run(){
System.out.println("run");
}
public void eat(){
}
}
子类student
public class student extends Person{
@Override
public void run() {
System.out.println("son");
}
public void eat(){
System.out.println("ear");
}
}
- 多态注意事项
- 多态是方法的多态,属性没有多态
- 父类和子类,有联系
- 存在的条件:继承关系,方法需要重写,父类引用指向子类对象 Father f1 = new Son();
instanceof
- 代码
import oop.day16.Person;
import oop.day16.Teacher;
import oop.day16.student;
public class Appliday16B {
public static void main(String[] args) {
//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object obj = new student();
//System.out.println(X instnceof Y);能不能编译通过
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(per instanceof Teacher);//编译报错
//System.out.println(per instanceof String);//编译报错
}
}
import oop.day16.Person;
import oop.day16.student;
public class Appliday16C {
public static void main(String[] args) {
//类型之间的转化,子类转换为父类,可能丢失自己的方法
student student = new student();
student.run();
Person person = student;
}
}
- 注意点
- 父类引用指向子类的对象
- 把子类转换为父类,向上转型
- 把父类转换为子类,向下转型;强制转换
- 转换的原因,方便方法的调用,减少重复代码