Q) What is the practical need of calling sub class constructor from within the sub class constructor explicitly? Give an example.
A)
-> to initialize the private variables of super class that belong to subclass object we need to call explicitly super class parameterized constructor from within subclass constructor.
class person
{
private int age;
person(int a)
{
age=a;
}
protected voiddisplaypersondetails()
{
System.out.println("age :"+age);
}
}
class Employeeone extends person
{
float salary;
Employeeone(float sal, int a)
{
super(a);// should be the first statement
salary=sal;
}
voiddisplayEmployeedetails()
{
System.out.println("salary Rs :"+salary);
displaypersondetails();
}
}
classexplicitconstructorcalling {
public static void main(String[] args) {
Employeeone explicit = new Employeeone(2000,45);
explicit.displayEmployeedetails();
}
}
Output:
salary Rs :2000.0
age :45
Comments
Post a Comment