Klasse Rechteck erstellen in Java?

2 Antworten

So:

class Point{
    private double x,y;
    public Point(){
        this.x = 0;
        this.y = 0;
    }
    public Point(double x, double y){
        this.x = x;
        this.y = y;
    }
    public double getX(){ return this.x; }
    public double getY(){ return this.y; }
    public void setX(double x){ this.x = x; }
    public void setY(double y){ this.y = y; }
}

class Size{
    private double width,height;
    public Size(){
        this.width = 0;
        this.height = 0;
    }
    public Size(double width, double height){
        this.width = width;
        this.height = height;
    }
    public double getWidth(){ return this.width; }
    public double getHeight(){ return this.height; }
    public void setWidth(double width){ this.width = width; }
    public void setHeight(double height){ this.height = height; }
}

class Rectangle{
    private Point position;
    private Size size;
    public Rectangle(){
        this.position = new Position();
        this.size = new Size();
    }
    public Rectangle(Point position, Size size){
        this.position = position;
        this.size = size;
    }
    public Rectangle(double x, double y, double width, double height){
        this.position = new Position(x, y);
        this.size = new Size(width, height);
    }
    public Point getPosition(){ return this.position; }
    public Size getSize(){ return this.size; }
    public void setPosition(Point position){ this.position = position; }
    public void setPosition(double x, double y){ this.position.setX(x); this.position.setY(y); }
    public void setSize(Size size){ this.size = size; }
    public void setSize(double width, double height){ this.size.setWidth(width); this.size.setHeight(height); }
    
    public double getArea(){ return this.size.getWidth() * this.size.getHeight(); }
    public double getCircumference(){ return 2 * this.size.getWidth() + 2 * this.size.getHeight(); }
}

P.S.: Auch wenn die Eigenschaft "position" vom Typ "Point" hier nicht direkt verwendet wird, kann es durchaus ne gute Idee sein, diese mit einzubauen um sie ggf. später zu verwenden (z.B. um eine Methode hinzuzufügen, die ermittelt, ob ein bestimmter Punkt innerhalb oder außerhalb des Rechtecks liegt; der auch für eine Methode zur ermittelung der Schnittpunkte des Rechtecks und einer Geraden; usw...).

public class Rechteck(){

double lange = 0;

double breite = 0;

Rechteck(double lange, double breite){

this.lange = lange;

this.breite = breite;

}

public double flache(){

return lange x breite;

}

public double umfang(){

return lange + lange + breite + breite;

}

}

Sollte stimmen. Eventuell, habs net getestet.


busspuss99  01.03.2018, 21:51

Ersetz "return lange x breite;" mit "return lange * breite;" dann funktioniert das 100%.

0