jash.liao的JAVA整理教學:JAVA件導向-介面
jash.liao的JAVA整理教學:JAVA件導向–介面
線上執行:http://www.tutorialspoint.com/compile_java_online.php / http://www.compilejava.net/
code2html:http://tohtml.com/
Java 的介面 (interface) 是一種參考型態 (reference type) ,使用關鍵字 interface 宣告及定義,同時 interface 已隱含 abstract ,介面中通常會定義的常數 (constant) 及方法 (method) ,其方法必須由類別 (class) 所實作 (implement) 。
介面的主要目的是制定軟體組件的共同規則,由於繼承 (inheritance) 只能由單一直線進行,也就是說子類別 (subclass) 只能繼承自某一特定的父類別 (superclass) 。介面提供了另一種彈性,使子類別在繼承父類別的特性之外,也能具有其他型態的特性。
interface Shape { publicdouble Shape_PI =3.14;
publicdouble area(); publicdouble perimeter(); }
class Circle implements Shape { privatedouble radius;
public Circle(double r){ setRadius(r); }
public Circle(){ this(10.0); }
publicdouble getRadius(){ return radius; }
publicvoid setRadius(double r){ if(r >0.0){ radius = r; } else{ radius =1; } }
publicdouble area(){ return radius * radius * Shape_PI; }
publicdouble perimeter(){ return2* radius * Shape_PI; } }
class Rectangle implements Shape { privatedouble length; privatedouble width;
publicRectangle(double l,double w){ setLength(l); setWidth(w); }
publicRectangle(double a){ this(a,10.0); }
publicRectangle(){ this(10.0,10.0); }
publicdouble getLength(){ return length; }
publicdouble getWidth(){ return width; }
publicvoid setLength(double l){ if(l >0){ length = l; } else{ length =1.0; } }
publicvoid setWidth(double w){ if(w >0){ width = w; } else{ width =1.0; } }
publicdouble area(){ return length * width; }
publicdouble perimeter(){ return2*(length + width); } }
publicclass HelloWorld{
publicstaticvoid main(String[]args){ System.out.println("Hello World"); Circle a =new Circle(15.6); System.out.println("Radius of the Circle:"+ a.getRadius()); System.out.println("Diameter of the Circle:"+ a.perimeter()); System.out.println("Area of the Circle:"+ a.area());
Rectangle b =newRectangle(20.0,16.0); System.out.println("Length of the Rectangle:"+ b.getLength()); System.out.println("Width of the Rectangle"+ b.getWidth()); System.out.println("Perimeter of the Rectangle"+ b.perimeter()); System.out.println("Area of the Rectangle"+ b.area()); } }
|