Home > OS >  How are we being able to access constructor of child in upcasting
How are we being able to access constructor of child in upcasting

Time:05-12

    public class Main {
            public static void main(String[] args) {
                Parent obj=new Child(1,2,3); //child constructor accessed during object creation
                System.out.println(obj.p);
                obj.fun()//error->how can I access constructor of child but not function of child 
            }
        }
    public class Parent {
        int p;
        Parent(int p){
            this.p=p;
            System.out.println("in parent");
    
        }
    }
    public class Child extends Parent {
        int c1,c2;

        Child(int c1,int c2,int p){
        super(p);
        this.c1=c1;
        this.c2=c2;
        System.out.println("in child");
    }
    public void fun(){
        System.out.println("fun");
    }
}

Q> I know that when variable type is parent object and object type is child, we can access the variables and methods of parent only and not that of child. My question is then how are we being able to access constructor of child?

CodePudding user response:

Instead of Parent object = new Child(1, 2, 3);,

Do Child object = new Child(1, 2, 3);

Now object will have all methods and fields of Parent and Child.

CodePudding user response:

You are confusing two entirely different things.

obj.fun() cannot be called because you have told the compiler that obj contains an object which may be of type Parent, or any possible unknown subclass. In theory, obj could be reassigned so it contains an object whose type is some other subclass of Parent which doesn’t have a fun() method at all, so the compiler cannot assume such a method exists.

This has nothing to do with a constructor. The constructors of a class, by definition, allow you to “create an instance from nothing.” They do not require an existing object of any type.¹

You can call new Child(1,2,3) for the same reason you can call new StringBuilder() without having an existing instance of StringBuilder (or any of its sublcasses or superclasses).


1. Actually, a constructor of a non-static inner class would require an existing instance, but that’s an uncommon case.

  • Related