final修饰的方法能否被继承?能否被重载?能否被重写?final修饰的类能否被继承?
首先我们先看下final在java中的作用
final在Java中可以用来修饰类、修饰方法和修饰变量
1. final修饰的类,为最终类,该类不能被继承。如String 类
2. final修饰的方法可以被继承和重载,但不能被重写
3. final修饰的变量不能被修改,是个常量
public class Person {
private String name;
private int age;
private String sex;
final public void work(){ //final 修饰的最终方法 可以被子类继承,但不能被重写
("a person can do work");
}
final public void work(int age){ //重载一个final类
("a person can do another work");
}
public void eat(){ //普通方法 可以被子类继承、重写
("a person need to eat");
}
public static void sleep(){ //静态方法 可以被继承
("a person need to sleep");
}
}
子类继承了父类Person 重写了父类普通方法eat() ,但不能重写父类final修饰的方法和静态方法
public class Man extends Person{
public void eat(){
("the man also need do eat");
}
public static void sleep(){
("the man also need to sleep");
}
}