class Animal{
int height;
int weight;
int age;
void move(){
}
} // end of class Animal
class Dog extends Animal{
Color hair;
void eat(){
}
void sleep(){
}
void bark(){
}
} // end of class Dog
class Test{
public static void main(String[] args){
Human h1 = new Human();
h1.printInfo();
Human h2 = new Human("小木");
h2.printInfo();
Human h3 = new Human("小婷",18);
h3.printInfo();
}// end of main(String[])
}
class Test {
public static void main(String[] args) {
Dog d1 = new Dog();
System.out.println(d1.getInfo());
Dog d2 = new Dog(30, 10);
System.out.println(d2.getInfo());
Dog d3 = new Dog("white");
System.out.println(d3.getInfo());
Dog d4 = new Dog(30, 10, "white");
System.out.println(d4.getInfo());
System.out.println("動物數量:" + Animal.totalCount);
System.out.println("狗狗數量:" + Dog.totalCount);
}// end of main(String[])
}// end of class Test
class A{
A(){
System.out.println("這裡是A的建構子");
}
}
class B extends A{
B(){
System.out.println("這裡是B的建構子");
}
}
class C extends B{
C(){
System.out.println("這裡是C的建構子");
}
}
建構一個C物件試試:
class Test {
public static void main(String[] args) {
C c = new C();
}// end of main(String[])
}// end of class Test
class A{
void printInfo(){
System.out.println("hello, I am A.");
}
}
class B extends A{
void printInfo(){
System.out.println("hello, I am B.");
}
}
class C extends A{
}
測試程式:
class Test {
public static void main(String[] args) {
B b = new B();
b.printInfo();
C c = new C();
c.printInfo();
}// end of main(String[])
}// end of class Test
class A{
// (↓關鍵字 final)
public final void printInfo(){
System.out.println("hello, this is A.");
}
}
class B extends A{
// 編譯錯誤! ↓ 利用final修飾的方法不能被覆寫。
public void printInfo(){
System.out.println("hello, this is B;");
}
}
在類別A的printInfo()方法利用關鍵字 final 修飾,所以任何繼承他的子類別都不能覆寫這個方法。 否則會產生編譯錯誤:『Cannot override the final method from A』。
第二點,程式範例:
class A{
public void printInfo(){
System.out.println("hello, this is A.");
}
}
class B extends A{
public void printInfo2Tina(){
System.out.println("hello Tina, nice to meet you <3");
}
}
恩,就是多定義一個方法,沒什麼好說的,這根本不是覆寫。
第三點,程式範例:
class A{
// 注意存取修飾子是(no modifier)
void printInfo(){
System.out.println("hello, this is A.");
}
}
class B extends A{
// ↓ 編譯錯誤,覆寫的方法存取權限小於覆寫對象
private void printInfo(){
System.out.println("hello, this is B.");
}
}
在A類別中的printInfo()方法修飾子是(no modifier),依據覆寫的開放權限規則,B類別繼承了A類別想覆寫printInfo(),覆寫的開放權限必須為public或protected或(no modifier),重點就是不能小於覆寫對象,否則會發生編譯錯誤:『Cannot reduce the visibility of the inherited method from A』。