2016-05-30 53 views
0

我有一個問題,可以說我有一個叫做public class School{}的類作爲超類。並將public class Student{} & public class instructor{}作爲子類。我有類調用public class SchoolDriver{}java超類顯示方法

我有一個方法叫

public void displayStudent(){ 
    super.display(); 
    System.out.println("I am student."); 
} 

上Student類。

我有一個關於教師班級叫

public void displayInstructor(){ 
    super.display(); 
    System.out.println("I am instructor."); 
} 

方法。

我呼籲public void display(){??????}在學校類的方法

如何在學校類的顯示方法寫displayInstructor()& displaystudent()?

+1

什麼叫 「顯示我的方法」 是什麼意思? –

+0

超類不知道這些方法「存在」。創建一個抽象方法並使子類實現它。你可以在超級課堂中叫它。 – user489872

+1

傳遞顯示中的字符串參數,在函數中傳遞它作爲super.display(「我是導師。」); –

回答

2

如何寫displayInstructor()& displaystudent()on學校的班級顯示方法?

根據提供的信息,這是不可能的。

我有一個叫做public class School{}的班,作爲一個超級班。並將public class Student{} & public class instructor{}作爲子類。

這個對象模型對我沒有意義。學生不是學校,講師也不是學校。繼承代表一個is-a的關係。所以想想學生,導師和學校駕駛員就好像他們是不同職業的人一樣。例如,你可能有一個Person類,它將成爲所有人的基類。

public class Person { 
    private String lastName; 
    private String firstName; 

    public Person(String firstName, String lastName) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
    } 

    public String getFullName() { 
     return this.firstName + " " + this.lastName; 
    } 

    @Override 
    public String toString() { 
     return getFullName(); 
    } 
} 

然後,您可能有相應的學生和講師代表的類。請注意,我會覆蓋toString()方法,而不是使用displayInstructor()displaystudent()

public class Student extends Person { 
    public Student(String firstName, String lastName) { 
     super(firstName, lastName); 
    } 

    @Override 
    public String toString() { 
     return getFullName() + " is student"; 
    } 
} 

public class Instructor extends Student { 
    public Instructor(String firstName, String lastName) { 
     super(firstName, lastName); 
    } 

    @Override 
    public String toString() { 
     return getFullName() + " is instructor"; 
    } 
} 

在代碼中的某處,您可以創建人員並調用toString()方法來顯示有關它們的信息。

Student student = new Student("John", "Smith"); 
Instructor instructor = new Instructor("John", "Rolfe"); 

System.out.println(student.toString()); 
System.out.println(instructor.toString()); 

,它將打印以下

John Smith is student 
John Rolfe is instructor