10/19/2010

BCS2234 Inheritance (2)


Pada Slide No 4 Chapter9 pelajar telah di beri contoh cara mengistharkan Superclasses dan subclasses. 4 class telah di istiharkan iaitu GeometricObject, Circle, Rectangle dan TestCircleRectangle (sila rujuk gambar di sebelah). Contoh tersebut menggunakan package (iaitu setiap satu class di di tulis dalam fail berasingan. Jika pelajar ingin mengumpulkan semua kelas dalam satu fail - Langkah yang perlu di buat ialah dengan membuang perkataan public pada setiap class yang dibina. Sila lihat contoh dibawah:-


/**
* @(#)Perwarisan.java
*
* Perwarisan application
*
* @author
* @version 1.00 2010/10/20
*/

public class Perwarisan {

public static void main(String[] args) {

// TODO, add your application code
System.out.println("Hello World!");
Circle circle = new Circle(1);
System.out.println("A circle " + circle.toString());
System.out.println(circle.getRadius());
System.out.println("The radius is " + circle.getRadius());
System.out.println("The area is " + circle.getArea());
System.out.println("The diameter is " + circle.getDiameter());

}
}


class GeometricObject { // perkataan public telah di buang
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;

/** Construct a default geometric object */
public GeometricObject() {
dateCreated = new java.util.Date();
}

/** Return color */
public String getColor() {
return color;
}

/** Set a new color */
public void setColor(String color) {
this.color = color;
}

/** Return filled. Since filled is boolean,
so, the get method name is isFilled */
public boolean isFilled() {
return filled;
}

/** Set a new filled */
public void setFilled(boolean filled) {
this.filled = filled;
}

/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}

/** Return a string representation of this object */
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
}

class Circle extends GeometricObject { // perkataan public telah di buang
private double radius;

public Circle() {
}

public Circle(double radius) {
this.radius = radius;
}

/** Return radius */
public double getRadius() {
return radius;
}

/** Set a new radius */
public void setRadius(double radius) {
this.radius = radius;
}

/** Return area */
public double getArea() {
return radius * radius * Math.PI;
}

/** Return diameter */
public double getDiameter() {
return 2 * radius;
}

/** Return perimeter */
public double getPerimeter() {
return 2 * radius * Math.PI;
}

/** Print the circle info */
public void printCircle() {
System.out.println("The circle is created " + getDateCreated() +
" and the radius is " + radius);
}
}

No comments:

Cara download Installer windows 10 dalam format ISO

1. Jika anda bercadang untuk download windows 10 melalui website rasmi windows - pilihan untuk download dalam format ISO tidak di berikan.  ...