View RSS Feed

Java Object

Class Methods

Rate this Entry
by , 04-26-2012 at 05:38 PM (491 Views)
If class method is defined by the subclass with similar sign as that of class method which is present in superclass, then in subclass the method present will be hiding the one which is present in superclass.
Distinction b/w overriding and hiding possess certain important implication. Overridden methodís version which is invoked is that one which is present in subclass. Hidden methodís version which is invoked is totally dependent upon whether it gets invoked by the subclass or superclass. Here is an example which possesses 2 classes. First one is an Animal that has 1 class method & one instance method.
Java Code:
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.");
    }
}
The second class which is a subclass of Animal is known as Cat:
Java Code:
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();
    }
}
Cat class, in Animal, overrides an instance method. It makes class method hidden, in Animal. In this class, main method forms the Cat instance and testClassMethod() is called at class & testinstanceMethod(), at the instance.

Program has an output, as following:

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

Submit "Class Methods" to Facebook Submit "Class Methods" to Digg Submit "Class Methods" to del.icio.us Submit "Class Methods" to StumbleUpon Submit "Class Methods" to Google

Categories
Inheritence

Comments