標籤:sys 蘋果 import width uil points 換行 build app
1. 類的繼承
繼承是物件導向編程技術的主要特徵之一,也是實現軟體複用的重要手段,使用繼承特性子類(subclass)
可以繼承父類(superclass)中private方法和屬性,繼承的目的是使程式碼重用,減少冗餘。
1.1 類的繼承的實現
·java語言中子類對父類的繼承是通過在子類定義時,使用關鍵字extends來實現的;
·如果定義一個java類時並未顯示的指定這個類的直接父類,則這個類預設繼承java.land.Object類
·繼承的特點,子類中的對象可以使用父類中的非private成員(方法和變數),故在子類中不必重寫,這就是繼承。
/** * Created by qichunlin on 2017/10/10. */public class Fruit { public String fruitName; public double weight; public void info() { System.out.print("我是一個"+fruitName+"~重"+weight+"g!"); }} public class Apple extends Fruit{ public static void main(String[] args){ Apple a=new Apple(); a.fruitName="蘋果"; a.weight=200; a.info(); } }2.方法的重載
·定義:是指在一個類中用相同的方法名字定義多個方法,當然每個方法應該具有不同的代碼,以實現不同的功能
方法的重載是實現多態性的重要手段。
·方法的名稱、類型和形式參數構成了方法的簽名,編譯器根據方法的簽名確定使用的是什麼方法,因此方法的簽名必須唯一。方法的傳回值類型對方法的簽名沒有影響,因此方法沒有傳回值
2.2 看下面一個例子
/** * Created by qichunlin on 2017/10/5. *//** 定義一個矩形類MyRect,重載buildRect方法描述一個矩形,如:可使用矩形的左上方和右下角座標,使用兩個點類的對象point,* */import java.awt.Point;class MyRect //定義矩形類{ int x1=0; //左上方座標初始化 int y1=0; int x2=0; //右下角座標初始化 int y2=0; MyRect buildRect(int x1,int y1,int x2,int y2) //方法1,左上方和右下角 { this.x1=x1; this.y1=y1; this.x2=x2; this.y2=y2; return this; } MyRect buildRect(Point topLeft,Point bottomRight) /*方法2,兩個point‘對象,指定左上方和右下角座標*/ { x1=topLeft.x; y1=topLeft.y; x2=bottomRight.x; y2=bottomRight.y; return this; } MyRect buildRect(Point topLeft,int w,int h) //方法3,左上方和寬度與高度 { x1=topLeft.x; y1=topLeft.y; x2=(x1+w); y2=(y1+h); return this; } void printRect() //列印輸出座標 { System.out.print("MyRect:<"+x1+","+y1); //列印後不換行 System.out.print(","+x2+","+y2+">"); //繼續上行列印 } public static void main(String[] args) { MyRect rect=new MyRect(); //建立對象 System.out.print("Calling buildRect with coordinates 25,25,50,50:"); //建立矩形1,調用方法1 rect.printRect(); //列印出座標 System.out.print("* * *"); System.out.println("Calling buildRect with points (10,10),(20,20):"); //矩形2,調用方法2 rect.buildRect(new Point(10,10),new Point(20,20)); rect.printRect(); //列印出座標 System.out.println("* * *"); System.out.print("Calling buildRect with 1 point(10,10),"); System.out.println("width(50)and height(50):"); rect.buildRect(new Point(10,10),50,50); //矩形3,調用方法3 rect.printRect(); //列印出座標 System.out.println("* * *"); }}
例子2:
/** * Created by qichunlin on 2017/10/7. */class MethodOverloading{ void receive(int i) { System.out.println("Received one int data"); System.out.println("i="+i); } void receive(float f){ System.out.println("Received one float data"); System.out.println("f="+f);}void receive(String s){ System.out.println("Received a String"); System.out.println("s="+s);}public static void main(String [] args){ MethodOverloading m = new MethodOverloading(); m.receive(3456); m.receive(34.56f); m.receive("方法重載"); }}
3.方法的重寫
方法的重寫是指在子類中使用與父類
2017.10.10 java程式設計-------繼承與多態