Thursday, March 12, 2009

What will the output of the following programme be? Look at the

Question :What will the output of the following programme be? Look at the
programme carefully, we have an instance method and
static method (class method) defined in both Animal class and Cat class.
public class Animal {
public static void hide() {
System.out.format("The hide method in Animal.%n");
}
public void override() {
System.out.format("The override method in Animal.%n");
}
}
public class Cat extends Animal {
public static void hide() {
System.out.format("The hide method in Cat.%n");
}
public void override() {
System.out.format("The override method in Cat.%n");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
//myAnimal.hide(); //BAD STYLE
Animal.hide(); //Better!
myAnimal.override();
}
}
(CoreJava)

Answer :The output of the programme will be..
The hide method in Animal.
The override method in Cat.
For class methods, the runtime system invokes the method defined in the
compile-time type of the reference on which the
method is called. In the example, the compile-time type of myAnimal is
Animal. Thus, the runtime system invokes the hide
method defined in Animal. For instance methods, the runtime system
invokes the method defined in the runtime type of the
reference on which the method is called. In the example, the runtime type
of myAnimal is Cat. Thus, the runtime system
invokes the override method defined in Cat.
An instance method cannot override a static method, and a static method
cannot hide an instance method.

No comments: