Using inherited fields after value update in inherited method

user13860 :

I am wrapping my head around inheritance in Java but I'm getting errors. I defined a superclass with a name field. As far as I know subclasses inherit fields and inherited fields can be assigned new values. I expected getArea() in the main to print triangle's Area value but I only get 0.0 printed. Hope you can help me. [updated example]

public class Figure{

double base;
double height;
double area;
public Figure(double base, double height){
this.height=height;
this.base=base;
}
public double getArea(){return area};
}


public class Triangle extends Figure(){
public Triangle(double base, double height){
super(base,height);
}
area=0.5 * base * height;
}


public class Main{

public static void main{
Triangle triangle=new Triangle();
System.out.println(triangle.getArea());
}

}
user2222 :

Here is a code that should work, with some notes

class Figure{

    double base;
    double height;
    double area;
    public Figure(double base, double height){
        this.height=height;
        this.base=base;
    }

    public double getArea(){return area;};
}


 class Triangle  extends Figure{
    public Triangle(double base,double height){
         super(base,height);
         this.area = 0.5*base*height;
    }

 }

public class Main{

    public static void main (String[] args){
        Triangle triangle=new Triangle(12,8);
        System.out.println(triangle.getArea());
    }

}
  1. You can't have more than a public class in one file
  2. When you explicitly define a constrictor , the default one won't be generated by the compiler so Triangle triangle=new Triangle() wont compile. In case you need to use the default constructor, you should declare it by yourself.
  3. Entry point main has a specific syntax that you should respect in order to be the first executed function in your program.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=344882&siteId=1