我想知道隐藏在java中的方法的实际用法.
对于前者
class MyClass{
public static void myMethod(){
//some code here
}
}
class MyClass1 extends MyClass{
public static void myMethod(){
//some code here
}
public static void main(String args[]){
MyClass1 obj1=new MyClass1();
MyClass obj=obj1;
MyClass.myMethod(); // this method will run the parent Class method myMethod then what is the use of this practically.
}
}
Run Code Online (Sandbox Code Playgroud)
首先,这不是一种压倒一切的形式.(当继承方法时会发生重写,并且staticJava中不会继承方法.)
这被称为"隐藏"......但有点像幻觉.访问隐藏的静态方法或字段非常容易.结果,这种"技术"并不是特别有用.
如果有的话,隐藏是一个坏主意,因为它可能是程序错误的来源......或者至少,代码来源看起来像是这样做但实际上做了不同的事情.
所以我的建议是避免隐藏而不是寻找使用它的地方.(事后看来,如果Java语言将其视为编译错误,可能会更好......)
为了记录,这是一个隐藏的例子:
public class A {
public static String method() { return "'A.method()'"; }
}
public class B extends A {
public static String method() { return "'B.method()'"; }
public static void main(String[] args) {
System.out.println(A.method()); // prints 'A.method()'
System.out.println(B.method()); // prints 'B.method()'
System.out.println(method()); // prints 'B.method()'
}
}
Run Code Online (Sandbox Code Playgroud)
在上面,版本method()中B隐藏了版本A,但无论如何你都可以调用它."隐藏"是一种幻觉.
这是一个示例,显示了它可能导致的问题类型:
A a = new A();
B b = new B();
System.out.println(a.method()); // prints 'A.method()'
System.out.println(b.method()); // prints 'B.method()'
b = a;
System.out.println(b.method()); // prints 'B.method()'
Run Code Online (Sandbox Code Playgroud)
它看起来像我们呼吁实例方法......直到你打三号method()呼叫.
还有另外两个术语 - "阴影"和"模糊" - 适用于不同的环境:
阴影是内部范围中的名称重新声明外部范围中的名称的位置.
模糊是您将名称用于成员,类型和/或包的位置.这个你真的想避免,因为它会导致真正令人困惑的代码.但幸运的是,你必须蔑视Java的标识符样式规则才能被这种方式所灼烧.