Suppose you have three classes A, B, and C. Modify the following classes so clas
ID: 3556454 • Letter: S
Question
Suppose you have three classes A, B, and C. Modify the following classes so class A inherits from class B, and class B inherits from class C.
public class A
{
private int x;
public A(int n)
{
x = n;
}
}
public class B
{
protected int x, z;
public B(int a, int b)
{
x = a;
z = b;
}
}
public class C
{
private String s;
public C(String x)
{
s = x;
}
}
Explanation / Answer
// Here i have used super keyword in the construtors.Hope this might help.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class C
{
private String s;
C(){
System.out.println("this is super class C");
}
void setC(String x)
{
this.s = x;
}
}
//Class B extending Class C using Keyword "extends"
public class B extends C
{
//previously Class B has protected x variable.and Class A has x variable of int type.this can be accessed in child class by providing Public access specifier like below.
public int x;
protected int z;
B(){
super();
System.out.println("this is class B");
}
void setB(int a, int b)
{
this.x = a;
this.z = b;
}
}
//Class A extending Class B using Keyword "extends"
public class A extends B
{
A(){
super();
System.out.println("this is class A");
}
//intially Class has declared variable x,but now as it is extending Class B,no need of declaring x.
void SetA(int n)
{
x = n;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.