在java中是否可以从构造函数调用函数

在java中是否可以从构造函数调用函数,java,Java,我试过这个: class rectangle{ rectangle(int a, int b){ int area(){ return(a*b); } } rectangle(int c){ int area(){ return(c*c); } } } class session1{ public static void main(String

我试过这个:

class rectangle{
    rectangle(int a, int b){
        int area(){
            return(a*b);
        }
    }
    rectangle(int c){
        int area(){
            return(c*c);
        }
    }
}
class session1{
    public static void main(String args[]){
        rectangle obj=new rectangle();
        System.out.println("The area of rectangle is: "+obj.area(20,10));
        System.out.println("The area of square is: "+obj.area(10));
    }
}
它显示错误:“;”预期 内部区域(){ ^
它应该有两个构造函数(两个参数和一个参数)来创建矩形或正方形的对象,并且它有一个名为area()的方法,该方法返回相应对象的面积

  • 用大写字母表示类,用小写字母表示属性/变量
  • 使用不同的构造函数,一个用于实数
    矩形
    ,另一个用于
    矩形
    ,它们是
    正方形

您尝试的不是从构造函数调用方法(这是完全可能的)但是在构造函数中定义一个方法。这不是有效的java。如果我在构造函数之外定义方法区域,那么我将如何从构造函数中调用它?请注意,最好的做法是以大写字母开头的类名,即
Rectangle
Session1
很好,您只需复制/粘贴即可我在编辑前给出的答案;)
class Rectangle{
    private int width;
    private int height;
    public Rectangle(int a, int b){
        this.width=a; this.height=b
    }
    public Rectangle(int c){
       this(c, c);
    }
    public int getArea(){
        return width*height;
    }
}
class session1{
   // two ways of using it
    public static void main(String args[]){
        System.out.println("The area of rectangle is: "+new Rectangle(20,10).getArea();
        Rectangle obj = new Rectangle(10);
        System.out.println("The area of square is: "+obj.getArea());
    }
}
class rectangle{
    private int a;
    private int b;
    rectangle(int a, int b){
        this.a=a; this.b=b;
    }
    rectangle(int c){
       this.a = this.b = c;
    }
    int area(){
        return a*b;
    }
}
class session1{
    public static void main(String args[]){
        System.out.println("The area of rectangle is: "+new rectangle(20,10).area());
        System.out.println("The area of square is: "+new rectangle(10).area());
    }
}