week4 practice Inheritance
Java 繼承練習:extends, super, constructor
附上兩個檔案,Person.java與Student.java
Person.java
/*
Person.java
**/
class Person {
String name;
int age;
static int x;
Person( String n, int a ){ // z構造方法是不能繼承的,子類要重新定義構造方法(爸爸有,兒子不一定有)
name = n;
age = a;
}
Person( String n ){
name = n;
age = -1;
}
Person( int age, String name )
{
this.age = age;
this.name = name;
}
Person( ){
this( 0, "" );
}
void sayHello(){
System.out.println("Hello! My name is " + name );
}
void sayHello( Person another ){
System.out.println("Hello," + another.name + "! My name is " + name );
}
boolean isOlderThan( int anAge ){
boolean flg;
if( age > anAge ) flg = true; else flg=false;
return flg;
}
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Student.java
class Student extends Person
{
String school;
int score;
void sayHello(Student another){
System.out.println("Hi!");
if (school== another.school) System.out.println(" Schoolmates");
}
boolean isGoodStudent(){
return score >=90;
}
void testThisSuper(){
int a;
a =age;
a = this.age;
a = super.age;// this.age is same as super
}
void sayHello(){
super.sayHello();// 調用父親類的sayhello,然後加一些行為
System.out.println( "My school is " +school);
}
Student(String name, int age, String school){ //構造方法是不能繼承的,子類要重新定義構造方法
super(name, age); // 調用父類的constructor,在Person.java 第7行,必須放在第一句
this.school =school;
}
//Student(){} // 27行已經定義,所以33行就不用默認
public static void main(String args[]){ // 父類對象與子類對象的轉換
Person p = new Person("Tom",50);
Student s = new Student("Andy",20, "NTU");
Student s3 = new Student("Mini",20, "NTU");
Person p2 = new Student("Bob",18, "NCKU");
Student s2 = (Student)p2; // 強制類型轉換(casting)
//Student s3 =(Student) p; // 編譯可以,執行不可行
s.sayHello();
System.out.println("--------------------");
p2.sayHello();
System.out.println("--------------------");
s.sayHello(p2);
s.sayHello(p);
System.out.println("--------------------");
p2.sayHello(s);
p2.sayHello(p);
System.out.println("--------------------");
s.sayHello(s3);
System.out.println("--------------------");
s3.sayHello(s);
Person []manypeople =new Person[100];
manypeople[0] = new Person("Li",18);
manypeople[1] = new Student("wong",18,"PKU");
}
}
Result:
Last updated
Was this helpful?