Expert Answer
- Comment
After corrections
Program:
class C1 { public int X; protected double Y; public char Z; C1(int a,double b,char c) { X=a; Y=b; Z=c; } public int GetX(){ return X; } public void setX(int a){ X=a; } public double GetY(){ return Y; } public void SetY(int b){ Y=b; } public void print(){ System.out.println("X="+X); System.out.println("Y="+Y); System.out.println("Z="+Z); } } class C2 extends C1 { private int A; C2(int a){ super(10,12.2,'A'); A=a; } public int GetA(){ return A; } public void SetA(int a){ A=a; } public void print(){ System.out.println("A="+A); } } public class Main { public static void main(String[] args) { C2 Obj1=new C2(10); System.out.println("X="+Obj1.X); System.out.println("Y="+Obj1.Y); System.out.println("Z="+Obj1.Z); } }
Answer:
Yes It is necessary to write constructor for C2 because in main class we are defining an object of class type C2 and we are trying to access class C1 data members i.e.,(X,Y,Z). so In C2 class constructor we have to call super() function which calls C1 constructor so that we can access C1 data members.
C2 class constructor:
C2(int a){
super(10,12.2,'A');
A=a;
}Output:
Have any doubts comment below..
PLss dont dislike....
ليست هناك تعليقات:
إرسال تعليق