In parent child relationship you can take the reference of parent and can create the object of child as you have done.
Superclass a;
a = new ChildClass();
but there is one condition that is the object a follows the blueprint of its reference class, which means that in your case a has a reference of Superclass so a has the access of all the methods which are defined in Superclass not in ChildClass.
So your call to a.setname("Roger"); is not valid because a is of type Superclass which doesn't have setname(String) method but if you do something likeChildClass a = new ChildClass()then your call toa.setname("Roger");will be valid becauseais of type ChildClass which hassetname(String) method.`
One more thing, lets suppose you have a structure as :
class SuperClass
{
public SuperClass();
public void setName(String name)
{
System.out.println("setName() of SuperClass with name "+name);
}
}
class ChildClass extends SuperClass
{
public ChildClass();
public void setName(String name)
{
System.out.println("setName() of ChildClass with name "+name);
}
}
and you call it in main like :
ChildClass a;
a = new ChildClass();
a.setname("Roger");
so it will compile and run fine with an output
setName() of ChildClass with name Roger.
and I am sure you know the real reason of this output now. :)
ChildClassso it will perform the function but in other cases this would break. I would suggest using interfaces to understand inheritance more completely.Superclass. It won't perform the function -- it won't even compile.