- 雙語版Java程序設計
- 何月順主編
- 205字
- 2018-12-27 20:14:11
2.11 Sample Program Practice
Example 2.1 Static Demo
//對靜態修飾符修飾的變量,可以直接用類名來調用 class StaticDemo{ static int a = 23; static int b = 23; static void callme(){ System.out.println("a = " + a); } } class Static{ public static void main(String args[]){ staticDemo.callme(); System.out.println("b = " + staticDemo.b); } }
Example 2.2 Inheritance
//實現繼承機制 class Box{ double width; double height; double depth; Box(){//構造函數1 width = height = depth = -1; } Box(double len) {//構造函數2 width = height = depth = len; } Box(double w, double h, double d) { //構造函數3 width = w; height = h; depth = d; } double volume(){ return width*height*depth; } } class boxWeight extends Box { //繼承了父類 double weight; boxWeight(double w, double h, double d, double wh){ width = w; height = h; depth = d; weight = wh; } double volume(){ return width*height*depth*weight; } } class Sample{ public static void main(String args[]){ boxWeight mybox1 = new boxWeight(10,11,12,13); double vol; vol = mybox1.volume(); System.out.println(vol); } }