Zoha Zoha - 4 months ago 10
Java Question

creating object with diffrenet refrence

I am so confused in this topic, Please help. Thankyou.
//a class (lets say B) extendes or implements another class or interface respectively

interface myInterfaceA{

int interfaceDataMember1;
int interfaceDataMember2;

void interfaceMethod1();
void interfaceMethod2();

}

class myClassA{

int parentClassDataMember1;
int parentClassDataMember2;

myclassA(){}

void parentClassMethod1(){}
void parentClassMethod2(){}

}


//case1

class B implements myInterfaceA{

int dataMember1;
int dataMember2;

B(){}

void method1(){}
void method2(){}
}


// OR case2

class B extends myClassA{

int dataMember1;
int dataMember2;

B(){}

void method1(){}
void method2(){}
}


// so in either case what is the purpose of creating the object of class B in the following way

myInterfaceA objectB = new B();
// or
myClassA objectB = new B();


1) is there any name of this procedure?
2) what (data memeber, methods, constructor ) will be loaded in objectB?
3) if all the code of class B will be loaded in the objectB then why did we give the refrece of interface or parent class?
4) is this shows polymorphism? if yes, then why?
5) in case2 will class B also inherit the constructor of myClassA
6) why the constructor of parentclass is also called whe we create child class object

Answer

1) is there any name of this procedure?

This is polymorphism.

2) what (data memeber, methods, constructor ) will be loaded in objectB?

Every data member and method will be inherited by the objectB.

In case of interfaces, the data members are private, static, final constants. They must be initialized in the constructor. The methods must be implemented by the class B.

In case of superclasses, the data members and methods are simply inherited. You can override the methods. Variables are not polymorphic.

3) if all the code of class B will be loaded in the objectB then why did we give the refrece of interface or parent class?

We give reference of interface or parent class so that in case of multiple subtypes, we can have a single method that accepts supertype instead of creating multiple methods. This reduces lines of code and makes the code readable.

4) is this shows polymorphism? if yes, then why?

This shows polymorphic behaviour so you don't need to bind each subtype to a different method. A single method can be written to dynamically bind all the subtypes of a single supertype.

5) in case2 will class B also inherit the constructor of myClassA

The constructor is not inherited. You must call explicitly super() if required.

6) why the constructor of parentclass is also called whe we create child class object

It is not mandatory to call the constructor of the parentclass everytime. You may skip it if it is not required. But as a standard practice, super() is the first line of the child class constructor, so that any changes in the super class object creation does not affect child class.