In: Computer Science
c. Why declaring data as protected doesn’t serve any meaningful purpose?
e. How does constructor calling works in an inheritance hierarchy?
In Java. Please answer give thorough answers 200-300 words
c: While declaring data as private can only be used by the class in which they are declared whereas protected data can be used in the subclass and also in the same package.So the thing is Protected acts as public within the class and its subclasses, but is hidden outside of those two cases. I'd say the disadvantage to protected is that people can subclass your class and create public getters/setters for it, therefore removing the intention of the access modifier.
e. Calling a constructor from the another constructor is known as Constructor chaining.The end of the chain will always be the Object's class constructor because every class is inherited from the Object class by default.In Java, constructor of base class with no argument gets automatically called in derived class constructor.For example:
class A
{
A()
{
System.out.println("Base class constructor");
}
}
class B extends A{
B(){
System.out.println("Derived class constructor");
}
}
public class abcmain{
public static void main(String args[])
{
B b=new B();
}
}
Here the output will be Base Class constructor and then Derived class constructor So it shows that base class constructor gets automatically called.But if we want to call parameterized constructor of base class then we have to use super() in derived class constructor and point to note is that super() command must be the first line in derived class constructor else it won't work.We can take an example to understand this,For example:
class A
{
A(int a)
{
System.out.println("Base class parameterized constructor");
}
}
class B extends A{
B(int x, int y){
int a=x;
super(a);
System.out.println("Derived class parameterized constructor");
}
}
public class abcmain{
public static void main(String args[])
{
B b=new B(5,4);
}
}
Now here the output will be Base class parameterized constructore and then Derived class parameterized constructor.
I hope you understood the concept.Thank you