class superClass {}
class subClass extends superClass{}
public class test
{
public static void main()
{
superClass sc1 = new subClass();
subClass sc
In both the cases, objects of subClass will be created, but the references will be different.
With the reference of superClass i.e sc1 , you won't be able to invoke the methods present in the subClass but not in the superClass. You will require casting to invoke the subClass methods.
Like :
class superClass {
public void superClassMethod(){
}
}
class subClass extends superClass{
public void subClassMethod(){
}
}
Now :
public class test
{
public static void main(){
superClass sc1 = new subClass();
subClass sc2 = new subClass();
//whats the difference between the two objects created using the above code?
sc2.subClassMethod(); //this is valid
sc1.subClassMethod(); // this is a compiler error,
// as no method named subClassMethod
// is present in the superClass as the
// reference is of superClass type
// for this you require a type cast
(subClass)sc1.subClassMethod(); // Now this is valid
}
}