Программирование на Java

       

public int sideA; public int


package demo.lang; public class Rectangle { public int sideA; public int sideB; public Rectangle(int x, int y) { super(); sideA = x; sideB = y; } public boolean equals(Object obj) { if(!(obj instanceof Rectangle)) return false; Rectangle ref = (Rectangle)obj; return (((this.sideA==ref.sideA)&&(this.sideB==ref.sideB))|| (this.sideA==ref.sideB)&&(this.sideB==ref.sideA)); } public static void main(String[] args) { Rectangle r1 = new Rectangle(10,20); Rectangle r2 = new Rectangle(10,10); Rectangle r3 = new Rectangle(20,10); System.out.println("r1.equals(r1) == " + r1.equals(r1)); System.out.println("r1.equals(r2) == " + r1.equals(r2)); System.out.println("r1.equals(r3) == " + r1.equals(r3)); System.out.println("r2.equals(r3) == " + r2.equals(r3)); System.out.println("r1.equals(null) == " + r1.equals(null)); } }
Пример 13.1.
Закрыть окно


r1.equals(r1) == true r1.equals(r2) == false r1.equals(r3) == true r2.equals(r3) == false r1.equals(null) == false
Пример 13.2.
Закрыть окно


package demo.lang; interface Vehicle { void go(); } class Automobile implements Vehicle { public void go() { System.out.println("Automobile go!"); } } class Truck implements Vehicle { public Truck(int i) { super(); } public void go() { System.out.println("Truck go!"); } } public class VehicleStarter { public static void main(String[] args) { Vehicle vehicle; String[] vehicleNames = {"demo.lang.Automobile", "demo.lang.Truck", "demo.lang.Tank"}; for(int i=0; i<vehicleNames.length; i++) { try { String name = vehicleNames[i]; System.out.println("look for class for: " + name); Class aClass = Class.forName(name); System.out.println("creating vehicle..."); vehicle = (Vehicle)aClass.newInstance(); System.out.println("create vehicle: " + vehicle.getClass()); vehicle.go(); } catch(ClassNotFoundException e) { System.out.println("Exception: " + e); } catch(InstantiationException e) { System.out.println("Exception: " + e); } } } }
Пример 13.3.
Закрыть окно


look for class for: demo.lang.Automobile creating vehicle... create vehicle: class demo.lang. Automobile Automobile go! look for class for: demo.lang.Truck creating vehicle... Instantiation exception: java.lang.InstantiationException look for class for: demo.lang.Tank Class not found: java.lang.ClassNotFoundException: demo.lang.Tank
Пример 13.4.
Закрыть окно

Содержание раздела