/*** 方法的重写实例*/
public class TestOverride {public static void main(String[] args) {Car h = new Car();Plane p = new Plane();h.run();h.getVehicle();p.run();}
}class Vehicle { //交通工具类public void run() {System.out.println("跑....");}public Vehicle getVehicle() {System.out.println("选择一个交通工具!");return null;}
}class Car extends Vehicle {
//重写了run()方法,但是 getVehicle() 还会运行@Overridepublic void run() {System.out.println("地上跑....");}//如果加上这一串代码, getVehicle() 也会被重写,输出结果为空
/*@Overridepublic Car getVehicle() {return new Car();} */
}class Plane extends Vehicle {
//重写了run方法()@Overridepublic void run() {System.out.println("天上飞....");}
}
public class Testfinal{public static void main(String[] args) {final int PI=3;PI =4;}
}
结果如图所示:
这里会报错,PI不能被重新赋值

public class Testfinal {public static void main(String[] args) {Student s=new Student();s.run();}
}class Person {public final void run() {System.out.println("正在运动");}}
class Student extends Person{public void run(){System.out.println("正在打篮球");}
}
结果如图所示:
final修饰的方法不能被重写,这里开发工具给我们的报错修改是删掉修饰run()方法的final。
删掉以后我们看看结果如何:
public class Testfinal {public static void main(String[] args) {Student s=new Student();s.run();}
}class Person {public void run() {System.out.println("正在运动");}}
class Student extends Person{public void run(){System.out.println("正在打篮球");}
}
运行结果如图所示:

public class Testfinal {public static void main(String[] args) {}
}final class Person {public void run() {System.out.println("正在运动");}}
class Student extends Person{}
结果如下图所示:
Person不能被继承,同样的我们把修饰Person类的final删掉,程序就不会报错了
