What does the super keyword represents and where can it be used? Give an example
ID: 3662610 • Letter: W
Question
What does the super keyword represents and where can it be used? Give an example of a superclass and subclass. Be sure to make all the instances variables of the super class private. Include at least one constructor in each class and ensure that the constructor of the subclass calls the constructor of the superclass. Also include a toString method in both classes that returns the values of the instance variables with appropriate labels. Ensure that the toString method of subclass calls the toString method of the superclass so that the string returned contains the values of all the inherited instance variables.
Explanation / Answer
Super keyword is used inside a sub-class method definition to call a public or
protected methods defined in the super class.
class sup_class
{
private int pass_year, age;
sup_class()
{
pass_year=2015;
age=18;
}
int toString_year()
{
return pass_year;
}
int toString_age()
{
return age;
}
}
class sub_class extends sup_class
{
sub_class()
{
super();
}
int toString_y()
{
return super.toString_year();
}
int toString_a()
{
return super.toString_age();
}
}
class super_main
{
public static void main(String args[])
{
sub_class o = new sub_class();
System.out.println("Year of Passing " + o.toString_y());
System.out.println("Age " + o.toString_a());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.