In: Computer Science
Can someone explain why this is the case? It would be much appreciated.
Consider the following class definitions:
public class Foo
{
public Foo() { }
public void method1()
{
System.out.println(’’Foo 1’’);
}
public void method2()
{
System.out.println(’’Foo 2’’);
}
}
public class Goo extends Foo
{
public Goo() { }
public void method1()
{
System.out.println(’’Goo 1’’);
}
}
public class Hoo extends Goo
{
public Hoo() { }
public void method2()
{
System.out.println(’’Hoo 2’’);
}
}
Given these class definitions, what will be the output of this code fragment?
Foo[] elements = new Foo[3];
elements[0] = new Hoo();
elements[1] = new Foo();
elements[2] = new Goo();
for (int i = 0; i < elements.length; i++) {
elements[i].method1();
elements[i].method2();
}
Answer:
Goo1
Hoo2
Foo1
Foo2
Goo1
Foo2
Here the classes are declared in Inheritance manner like parent and child class.
If the child class and their parent class have same methods with same signature then those methods are called as "method overriding" . In method overriding what it will do is it checks for which class object is created.For that class we call a method if the method is present in that class it will execute that method or else It goes to it's parent class to check for that method if it is present in that method then it executes that method.This process continues until we get the first parent of class.
For the object created for Hoo() it has method 2 not method 1 so,it takes method 1 from Goo and method 2 from itself.
For Foo() it is the main class so,it directly executes it's own methods
For Goo() it has method 1 only so,it executes method 1 and goes it's parent Foo() for method 2
If we want to execute the methods of parent class from the child we have to use"Super" Keyword.If we use super keyword in child it goes to it's Parent class for execution
----------------------------------------------------------------------------------------------
Foo[] elements = new Foo[3];
elements[0] = new Hoo();
elements[1] = new Foo();
elements[2] = new Goo();
for (int i = 0; i < elements.length; i++) {
elements[i].method1();
elements[i].method2();
}