生活随笔
收集整理的這篇文章主要介紹了
Java 抽象类、接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
抽象類定義規則如下:
(1) 抽象類和抽象方法都必須用 abstract 關鍵字來修飾。
(2) 抽象類不能被直接實例化,也就是不能用new關鍵字去產生對象。
(3) 抽象方法只需聲明,而不需實現。
(4) 含有抽象方法的類必須被聲明為抽象類,抽象類的子類必須覆寫所有的抽象方法后才能被實例化,否則這個子類還是抽象的
abstract class Person2 { String name
;int age
;String occupation
;public abstract void talk();public Person2(String name
, int age
, String occupation
){this.name
= name
;this.age
= age
;this.occupation
= occupation
;}
}class Student1 extends Person2
{public Student1(String name
, int age
, String occupation
){super(name
, age
, occupation
);}public void talk(){System
.out
.println("覆寫talk()");}
}class test2{public static void main(String
[] args
){Student1 s
= new Student1("Ming", 18, "student");s
.talk();}
}
- interface 接口
數據成員全部是常量 final 初始化
所有方法全部是 abstract 抽象的,沒有一般方法
Java 沒有多重繼承,但是可以使用 接口 來實現 多繼承
class 類名 implements 接口A, 接口B
接口 可以繼承于 多個 接口
interface 接口C extends 接口A, 接口B
interface Person3 {final String name
= "Michael"; int age
= 18;String occupation
= "工程師";public abstract void talk1();
}
interface Worker1{String tool
= "hammer";
}
class Student2 implements Person3, Worker1
{public void talk1(){System
.out
.println("name: " + this.name
+ ", age: " + this.age
+ ", occupation: " + this.occupation
+ ", tool: " + this.tool
);}
}
interface AnotherInterface extends Person3, Worker1
{String state
= "person3+worker1";public void talk2();
}class Student3 implements AnotherInterface{public void talk1(){System
.out
.println("每個抽象方法要覆寫,talk1()");}public void talk2(){System
.out
.println("每個抽象方法要覆寫,talk2()");}
}
class test3
{public static void main(String
[] args
){Student2 s2
= new Student2();s2
.talk1();Student3 s3
= new Student3();s3
.talk1();s3
.talk2();}
}
輸出:
name
: Michael
, age
: 18, occupation
: 工程師
, tool
: hammer
每個抽象方法要覆寫
,talk1()
每個抽象方法要覆寫
,talk2()
總結
以上是生活随笔為你收集整理的Java 抽象类、接口的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。