I am learning java for the last one week, sorry for the dumb question but if i just declare a variable in the parent class without storing any value in it, maybe use a setter or constructor for inputing its value then can I work with those values/properties of the parent class in a child class?
class circle2
{
double radius;
double Area;
Scanner Sc = new Scanner(System.in);
void SetRadius() {
System.out.println("Enter Radius");
radius = Sc.nextDouble();
}
}
class cylinder2 extends circle2
{
double height=5,volume;
void GetVolume(){
volume=Math.PI*radius*radius*height;
System.out.println("Volume of cylinder : " volume);
}
}
public class Ch10Alternate_PS {
public static void main(String[] args) {
circle2 obj = new circle2();
obj.SetRadius();
cylinder2 obj1 = new cylinder2();
obj1.GetVolume();
}
}
This gives me a value of 0.0 for volume
CodePudding user response:
You are creating two objects, a circle and a cylinder. You are setting the radius of the circle. Then you are calculating the volume of the cylinder. Which result do you expect?
The solution is to set the radius of the cylinder:
cylinder2 obj1 = new cylinder2();
obj1.SetRadius();
obj1.GetVolume();
Sample session:
Enter Radius
3
Volume of cylinder : 141.3716694115407
The problem really had not got anything to do with what was in the parent class and what was in the child class. It all ends up in the same object when you create one.