iT邦幫忙

2024 iThome 鐵人賽

DAY 24
0
自我挑戰組

前端工程師的java學習紀錄系列 第 24 篇

Day24-抽象、abstract

  • 分享至 

  • xImage
  •  

抽象指的是當今天一個super class 有很多的sub class 時,本身所提供的方法 可能已經不符合每一個sub class 所要做的事情了,這時候可以使用抽象的概念,將super class 轉換為抽象類,並且在每一個sub class將super class中的方法重寫。

使用abstract 可以將類轉為抽象,加上abstract 的class 是不能使用new Person() 的方式將其實例化。

public abstract class Person {}

public class Student extends Person {}

在方法前加上abstract 也可以將方法變為抽象方法 ,這時的方法是不可以包含程式碼區塊 的,且當class 中有abstract method 時,該class 也需要變為abstract class。

public abstract class Person {
	public abstract void eat();
}

public class Student extends Person {
	public void eat() {
		System.out.println("I am eatting");
	}
}

💡當繼承抽象類 時,要小心一定得將super class 中的抽象方法 實現,否則這個sub class 也會成為一個抽象類 ,那就無法正常使用它了。

abstract不能跟這些一起使用:

  • 使用private的方法:不可以被重寫
  • 靜態方法 :靜態方法 可以透過class 本身去使用,這樣就違反了abstract method 沒有程式碼區塊 的部分
  • 使用final 的方法:使用final 的方法無法被重寫,abstract 強調的是透過sub class重寫方法
  • 使用final 的類:使用final 的類無法被繼承,這也違反了abstract 的用法

舉例使用:

  1. 使用抽象的方式創造一個Person 的super class ,當中屬性有String name 、int age 、int height 、int weight ,並且有一個抽象的方法 是String introduce。
  2. 創造一個Student 的sub class ,當中屬性有String school ,有兩個構造器。
  3. 創造一個Teacher 的sub class ,當中當中屬性有String teach ,有兩個構造器。
public abstract class Person {
	String name;
	int age;
	int height;
	int weight;
	
	public abstract String introduce();
}
public class Student extends Person {
	String school;
	public Student() {};
	public Student(String name, int age, int height, int weight, String school) {
		super(name, age, height, weight);
		this.school = school;
	}
	
	public String introduce() {
		return "I am " + name + ", I am " + age + " years old. I study in" + school + ".";
	}
}
public class Teacher extends Person {
	String teach;
	public Teacher() {};
	public Teacher(String name, int age, int height, int weight, String teach) {
		super(name, age, height, weight);
		this.teach = teach;
	}
	
	public String introduce() {
		return "I am " + name + ", I am " + age + " years old. I teach" + teach + ".";
	}
}
public class School {
	public static void main(String[] args) {
		Person[] person = new Person[2];
		person[0] = new Student("Tom", 15, 187, 78, "Hello School");
		person[1] = new Teacher("Amy", 27, 153, 42, "Math");
		
		for(int i = 0; i < person.length; i++) {
			System.out.println(person[i].introduce());
		}
	}
}
I am Tom, I am 15 years old. I study in Hello School.
I am Amy, I am 27 years old. I teach Math.

可以看到這邊使用多態的方式去宣告一個Person 的陣列 ,但是每一個內容則是使用sub class 去建立。


上一篇
Day23-final
下一篇
Day25-接口interface
系列文
前端工程師的java學習紀錄 共 41 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言