What does the super keyword represents and where can it be used? Give an example
ID: 3845618 • 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
In Inheritance when in super class and subclass both have variables with same name then super class variable is still inherited but it is hidden by the varable in the sub class. We can reffer to the super class member by qualifying them with the keyword super.
ex. super.variablename
super.method()
Example
class one
{
private int x;
one(int a)
{
a=x;
}
public void show()
{
System.out.print("x : " + x);
}
class Two extends One
{
int x;
Two(int a, int b)
{
super(a);
x=b;
}
public void show()
{
super.show();
System.out.print("y = " + x);
}}
class Demo
{
public static void main(String args[])
{
Two t=new Two();
t(3,4);
t.show();
}}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.