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

时间:2018-01-26 16:14:59

标签: 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 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));
    }
}

显示错误:';'预期         int area(){                 ^ 它应该有两个构造函数(带有两个参数和一个参数)来创建对象为矩形或正方形,并且它有一个名为area()的方法,它返回相应对象的区域

2 个答案:

答案 0 :(得分:10)

你没有以一种好的方式设计它:

  • 使用UpperCaser为classes命名,lowerCaser为attributs / variables
  • 使用不同的构造函数,一个用于实际Rectangle,另一个用于Rectangle square
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());
    }
}

答案 1 :(得分:1)

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());
    }
}