[英]Correct use of 'extend' class in java
假設我有一個帶有通用函數的Math類,例如
public class math {
public double add(int a, int b){
//code
}
}
我有一類“ students
”,希望使用上面的“ add
”方法。 我可以給學生上數學課嗎? 還是創建它的實例? 例如
math a = new math();
a.add
將add函數設置為靜態會更有意義,例如,可以在Student類中執行Math.add(1,1)
。
讓Student
擴展Math
是沒有意義的,因為學生不是數學對象。 學生是一個人,因此您可以開設一個Person
類,然后讓Student extends Person
。
如果要使兩個方法具有某種程度上相似的add
方法, 可以執行的操作是創建一個接口Addable
,該接口聲明存在這種add
方法。 它可能看起來像這樣:
public interface Addable<S, T, U> {
S add(T a, U b);
}
和
public class Student implements Addable<Student, Student, Integer> {
private int age;
Student(int age) {
this.age = age;
}
public Student add(Student a, Integer b) {
return new Student(a.age + b);
}
public int getAge() {
return age;
}
}
和
public class Math implements Addable<Double, Integer, Integer> {
public Double add(Integer a, Integer b) {
return Double.valueOf(a + b);
}
}
但是 這只是為了解釋繼承是如何工作的 ; 像這樣的add
方法沒有什么意義,因為其他答案已經指出。 像這樣(獨立於對象實際實例的函數)應該是static
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.