Experimento de Java: clases y objetos
Salida:
Ejemplo 1:
Largo: 10
Ancho: 5
Área: 50
Perímetro: 30
Ejemplo 2:
Largo: 20
Ancho: 10
Área: 200
Perímetro: 60
// Clase de rectángulo de diseño
clase Rentangle {
// Constructor sin argumentos
public Rentangle() {
}
// Constructor con parámetros
public Rentangle(largo alto, largo ancho) {
this.height = altura;
this.width = ancho;
}
// largo
alto largo privado; p>
// ancho
private long ancho;
public long getHeight() {
return this.height;
p>}
public long getWidth() {
return this.width;
}
public void setHeight( altura larga ) {
this.height = altura;
}
public void setWidth(ancho largo) {
this.width = ancho ;
}
// Área
public long area() {
devuelve este.alto * este.ancho
; p>
}
// Circunferencia
public long circunferencia() {
return 2*this.height 2 * this.width ; p>
}
}
clase pública TestRentangle {
public static void main(String[] args) {
// Inicializa el objeto a través del constructor sin argumentos
Rentangle rentangle1 = new Rentangle();
rentangle1.setHeight(10);
setWidth. (5);
// Imprime su largo, ancho, área y perímetro.
System.out.println("Instancia 1: ");
System.out.println("Largo: " rentangle1.getHeight()); > System.out.println("Ancho: " rentangle1.getWidth());
System.out.println("Área: " rentangle1.area());
Sistema .out.println("Perimeter: " rentangle1.circumference());
// Inicializa el objeto a través del constructor con parámetros
Rentangle rentangle2 = new Rentangle(20, 10) ;
// Imprime su largo, ancho, área y perímetro
System.out.println("Ejemplo 2:
System .out); .println("Longitud: " rentangle2.getHeight());
System.out.println("Ancho: " rentangle2.getWidth());
System.out .println ("Área: " rentangle2.area());
System.out.println("Perímetro: " rentangle2.circumference());
}
}