Java中的方法隐藏的教程

381 阅读2分钟

先决条件Java中的重写

如果一个子类定义的静态方法与超类中的静态方法具有相同的签名,那么子类中的方法就会隐藏超类中的方法。这种机制的发生是因为静态方法是在编译时解决的。静态方法在编译时使用引用的类型而不是对象的类型进行绑定。

例子

java

// Java program to demonstrate
// method Hiding in java
  
// Base Class
class Complex {
    public static void f1()
    {
        System.out.println(
            "f1 method of the Complex class is executed.");
    }
}
  
// class child extend Demo class
class Sample extends Complex {
    public static void f1()
    {
        System.out.println(
            "f1 of the Sample class is executed.");
    }
}
public class Main {
  
    public static void main(String args[])
    {
        Complex d1 = new Complex();
  
        // d2 is reference variable of class Demo that
        // points to object of class Sample
        Complex d2 = new Sample();
  
        // But here method will be call using type of
        // reference
        d1.f1();
        d2.f1();
    }
}

输出。

f1 method of the Complex class is executed.
f1 method of the Complex class is executed.

程序演示Java中方法覆盖和方法隐藏的区别。

Java

// Java program to demonstrate
// Difference between method overriding and Method hiding
  
// Base Class
class Complex {
    public static void f1()
    {
        System.out.println(
            "f1 method of the Complex class is executed.");
    }
  
    public void f2()
    {
        System.out.println(
            "f2 method of the Complex class is executed.");
    }
}
  
// class child extend Demo class
class Sample extends Complex {
    public static void f1()
    {
        System.out.println(
            "f1 of the Sample class is executed.");
    }
    public void f2()
    {
        System.out.println(
            "f2 method of the Sample class is executed.");
    }
}
public class Main {
  
    public static void main(String args[])
    {
        Complex d1 = new Complex();
          
         // d2 is the reference variable of class Demo that
        // points to object of class Sample
        Complex d2 = new Sample();
          
        // But here method will be called using type of
        // reference
        d1.f1();
        d2.f1();
  
        // ***** Function overriding in java *****//
        // method refer to the  object  in the method
        // overriding.
        d1.f2();
        d2.f2();
    }
}

输出。

f1 method of the Complex class is executed.
f1 method of the Complex class is executed.
f2 method of the Complex class is executed.
f2 method of the Sample class is executed.

Java中方法重写和方法隐藏的区别

  • 在方法覆盖中,方法的父类和子类都是非静态的。
  • 在方法隐藏中,方法的父类和子类都是静态的。
  • 在方法Overriding中,方法的解析是基于引用类型的。
  • 在方法中,隐藏方法在对象类型的基础上解决。
  • 被调用的重写实例方法的版本是子类中的那个。
  • 被调用的隐藏静态方法的版本取决于它是在超类还是在子类中被调用。
  • 方法覆盖被称为编译时多态性或静态多态性或早期绑定。
  • 方法隐藏被称为运行时多态性或动态多态性或后期绑定。