Java 中静态方法的隐藏
当超类和子类包含相同的实例方法(包括参数)时,调用时,子类的方法会覆盖超类的方法。
示例
class Super{
public void sample(){
System.out.println("Method of the Super class");
}
}
public class MethodOverriding extends Super {
public void sample(){
System.out.println("Method of the Sub class");
}
public static void main(String args[]){
MethodOverriding obj = new MethodOverriding();
obj.sample();
}
}输出
Method of the Sub class
方法隐藏
当超类和子类包含相同的方法(包括参数)并且它们是静态的时,超类中的方法将被子类中的方法隐藏。这种机制称为方法隐藏。
示例
class Super{
public static void demo() {
System.out.println("This is the main method of the superclass");
}
}
class Sub extends Super{
public static void demo() {
System.out.println("This is the main method of the subclass");
}
}
public class MethodHiding{
public static void main(String args[]) {
MethodHiding obj = new MethodHiding();
Sub.demo();
}
}输出
This is the main method of the subclass
原因
方法重载的关键是,如果超类和子类具有相同签名的方法,则对于子类的对象,两者都可用。根据您用来保存对象的类型(引用),将执行相应的方法。
SuperClass obj1 = (Super) new SubClass(); obj1.demo() // invokes the demo method of the super class SubClass obj2 = new SubClass (); obj2.demo() //invokes the demo method of the sub class
但是,对于静态方法,由于它们不属于任何实例,因此需要使用类名来访问它们。
SuperClass.demo(); SubClass.Demo();
因此,如果超类和子类具有相同签名的静态方法,尽管超类方法的副本可用于子类对象。由于它们是静态的,因此方法调用在编译时本身就会解析,静态方法无法被重写。
但是,由于静态方法的副本可用,如果您调用子类方法,则超类的方法将被重新定义/隐藏。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP