Let's say I have a class 'Person' and another class 'Survey' which extends person so Survey is the child class and Person class is the parent. Person was the first class I wrote and hence defined the main method there now since I have a child class, can I call methods of the child class from the main method in the parent class (or do I need to keep transferring the main method to the class that is lower most in the heirarchy although I am pertty sure this is never ever going to be necessary...)? If so is this not counter intuitive to the notion that the child class inherits attributes of the parent class but the parent class does not inherit any attributes of the child class? Please do oblige with a reply. Thanks in advance.
Also I also read another post of having a separate class maybe 'driver.java just for the main method so would this mean that all classes would have to be imported into this class for us to call methods from other class in the main method?
I hope my question is not too convoluted.
Let me explain it to you,
When you create an instance of the Subclass by calling new
on the sub class type
, then immediately
its Super class constructor is called
, and it keeps going till
the Object class
, this is called Constructor chaining
.
All the instance variable
are declared and initialized
during this process.
And most important
is that when constructor of subclass it called it goes to its super class and so on till the Object class, then 1st creating the Object class object
, then the class under
it, till it reaches the subclass on whose class new was called
, You will see that the constructor of the super class is called first then its subclass's
And for your above question i have also created an example which fits appropriately with the theoretical explanation i have given.
eg:
public class a {
public static void main(String[] args) {
B b = new B();
b.go();
}
}
class B extends a{
public void go(){
System.out.println("hello");
}
}