Let's say I have a piece of code:
class one
{
String one = "First";
}
class sec extends one
{
String sec = "Second";
}
class num
{
public static void main(String[] args)
{
one o = new one();
sec s = new sec();
one oo = new sec();
// the object will be of that class for which we are providing the reference
// then what is the use of the constructor
sec s = new one(); // this is not working
System.out.println(o.one);
System.out.println(s.sec);
System.out.println(oo.one); # this seems right
System.out.println(oo.sec); # this is not working
}
}
I am confused by the reference and the constructor while creating the object.
I have extended the sec
class to inherit from class one
.
I got the meaning of first two object creation that we are referencing to the one
class and creating the object same for the second object.
But what about the third object? We are using the reference of the class one and providing the constructor of the child class and I can use the third object(oo) just to refer the variable and methods of the one class not second class.
If I have to use the methods and variables of one class then I can use it with the object(o) rather than object(oo). So what is the difference between both the objects when they are behaving like each other?
one o = new one();
one oo = new sec();
I want to know the difference between these two that what are the changes come when we use the constructor of the child class rather than the base class.