一. 抽象類ide
1. 抽象類:包含了一個抽象方法的類就是抽象類this
2. 抽象方法:聲明而未被實現的方法,用關鍵字abstract聲明spa
3. 抽象類被子類繼承,子類(若是不是抽象類)必須重寫(override)抽象類中的全部抽象方法code
4. 定義格式:對象
abstract class className{ 屬性 方法 抽象方法 }
5. 抽象類不能被直接實例化,要經過其子類進行實例化blog
抽象類的應用繼承
1 package com.bruceyo.absdemo; 2 3 //抽象類的應用 4 abstract class Person{ 5 private int age; 6 private String name; 7 public Person(int age, String name){ 8 this.age = age; 9 this.name = name; 10 } 11 public void tell(){ 12 13 } 14 15 public int getAge() { 16 return age; 17 } 18 19 public void setAge(int age) { 20 this.age = age; 21 } 22 23 public String getName() { 24 return name; 25 } 26 27 public void setName(String name) { 28 this.name = name; 29 } 30 31 public abstract void want(); 32 33 } 34 class Student extends Person{ 35 private int score; 36 37 public int getScore() { 38 return score; 39 } 40 41 public void setScore(int score) { 42 this.score = score; 43 } 44 45 public Student(int age, String name, int score) { 46 super(age, name); 47 this.score = score; 48 // TODO Auto-generated constructor stub 49 } 50 51 @Override 52 public void want(){ 53 System.out.println("Name:"+getName()+", Age:"+getAge()+", Score:"+getScore()); 54 } 55 56 } 57 class Worker extends Person{ 58 private int money; 59 60 61 public int getMoney() { 62 return money; 63 } 64 65 public void setMoney(int money) { 66 this.money = money; 67 } 68 69 public Worker(int age, String name, int money) { 70 super(age, name); 71 this.money = money; 72 // TODO Auto-generated constructor stub 73 } 74 75 @Override 76 public void want(){ 77 System.out.println("Name:"+getName()+", Age:"+getAge()+", money:"+getMoney()); 78 } 79 80 } 81 82 public class AbsDemo { 83 84 public static void main(String[] args) { 85 // TODO Auto-generated method stub 86 Student student = new Student(55,"Bruce",4); 87 student.want(); 88 Worker worker = new Worker(66, "Json", 6666); 89 worker.want(); 90 91 } 92 93 }
二. 接口接口
1. 接口能夠理解爲一種特殊的類,裏面所有是由全局常量和公共的抽象方法所組成get
2. 定義格式:event
interface interfaceName{ 全局常量 //e.g. public static final int AGE = 100; 抽象方法 //e.g. public abstract void tell(); }
3. 接口實現必須經過子類,使用關鍵字implements, 並且接口是能夠多實現的
4. 一個類能夠同時繼承抽象類和實現接口
5. 一個接口不能繼承一個抽象類,可是能夠經過extends關鍵字同時繼承多個接口,實現接口多繼承
接口的應用
package com.bruceyo.absdemo; interface USB{ //制定一個標準,每個USB必須按照這個標準進行工做 void start();//可省略public abstract void stop(); } class C{ //接口的實例 public static void work(USB u){ u.start(); System.out.println("Working"); u.stop(); } } class USBDisk implements USB{ public void start(){ System.out.println("USBDisk start Working"); } public void stop(){ System.out.println("USBDisk stop Working"); } } class Printer implements USB{ public void start(){ System.out.println("Printer start Working"); } public void stop(){ System.out.println("Printer stop Working"); } } public class InterfaceDemo { public static void main(String[] args) { // TODO Auto-generated method stub C.work(new USBDisk()); C.work(new Printer()); } }
多態性:
方法的重載和重寫
對象的多態性
向上轉型:程序自動完成
向下轉折:強制類型轉換