Hello I am new to Java and learning Inheritance.
This is my code:
import java.util.Scanner;
import java.lang.Math;
class Circle{
double radius;
Circle(double radius){
this.radius = radius;
}
double area(){
return((Math.PI)*Math.pow(radius,2));
}
}
class Sector extends Circle{
double radians;
int radius;
Sector(int radius , double radians){
super(radius);
this.radians = radians;
}
double area(){
return 1/2 * radius*radius * radians;
}
}
public class Inherit{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("enter radius of circle");
int radius = sc.nextInt();
System.out.println("Ener radians");
double rad = sc.nextDouble();
Sector c = new Sector(radius , rad);
System.out.println("area is:" + c.area());
}
}
However cant really understand why the area im getting is 0.
Any suggestions appreciated.
Another thing that I didnt understand is the fact that, if the change the
Sector(int radius , double radians){
super(radius);
this.radians = radians;
}
to,
Sector(int radius , double radians){
this.radius = radius;
this.radians = radians;
}
the compiler throws another error.Can anyone please explain these two abominations?
>Solution :
You have to remove the radius in your Sector class and you have to fix the method area in this way:
double area() {
return 1 / 2d * radius * radius * radians;
}
The operation 1 / 2 is a division between integers than the result is 0.
0 * radius * radius * radians
If you put 2d, the division 1 / 2d will be double.
0.5d * radius * radius * radians