类方法子类和父类

来源:互联网 发布:淘宝上老款诺基亚来源 编辑:程序博客网 时间:2024/05/29 08:49
public class Animal {    public static void testClassMethod() {        System.out.println("The class method in Animal.");    }    public void testInstanceMethod() {        System.out.println("The instance method in Animal.");    }}
public class Cat extends Animal {    public static void testClassMethod() {        System.out.println("The class method in Cat.");    }    public void testInstanceMethod() {        System.out.println("The instance method in Cat.");    }    public static void main(String[] args) {        Cat myCat = new Cat();        Animal myAnimal = myCat;        Animal.testClassMethod();        myAnimal.testInstanceMethod();    }}


The class method in Animal.The instance method in Cat.


Summary

The following table summarizes what happens when you define a method with the same signature as a method in a superclass.

Defining a Method with the Same Signature as a Superclass's Method Superclass Instance MethodSuperclass Static MethodSubclass Instance MethodOverridesGenerates a compile-time errorSubclass Static MethodGenerates a compile-time errorHides


Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass.

原创粉丝点击