Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inheritance in Java and super calling

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading