天天看點

Java 面向對象:繼承多态、覆寫override

package com.neusoft.override;

public class A {
	public String toString() {
		return "123456";// 繼承Object并重寫

	}

	int a = 2;

	public void func() {
		System.out.println("1111111111");
	}

	public static void main(String[] args) {
		A a = new A();
		System.out.println(a);// 等同于a.toString()預設
	}

}
           
package com.neusoft.override;
/**
 * 繼承多态
 * 滿足多态的條件:
 * 1.要有繼承關系
 * 2.方法重寫
 * 3.父類的引用指向子類的對象
 * @author Administrator
 *
 */
public class B extends A {
	int a = 2;

	public void func() {
		System.out.println("2222222222");
	}

	public static void main(String[] args) {
//		B b = new B();
//		b.func();//2222222222
//		System.out.println(b.a);//2
		
		//多态
		A x = new B();//父類引用指向子類
		x.func();//無論如何,涉及到重寫,就執行子類2222222222
		System.out.println(x.a);//1
		 
		A a = new A();
		a.func();//1111111111
		
		
	}
}
           
package com.neusoft.override;

/**
 * 方法的覆寫override: /重寫rewrite
 * 1.要有繼承關系
 * 2.子類要重寫父類中的方法,要求子類中的方法完全相同(通路權限,方法名稱,參數,傳回值類型)
 * 3.為什麼要使用方法重寫?子類的方法對象父類方法的拓展與改造
 * 
 */
public class Person {
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	

	
	public void printInfo() {
		System.out.println(name+"----"+age);
	}
}
           
package com.neusoft.override;


public class Student extends Person{
	private String school;
	
	public String getSchool() {
		return school;
	}

	public void getSchool(String school) {// overload 重載
		this.school = school;// 初始化

	}
	
	public void printInfo(){
		setAge(2);
		System.out.println(getName()+getAge()+school);
		
	}
	public static void main(String[] args) {
		Student student = new Student();
		student.printInfo();
		Person person = new Person();
		person.printInfo();
		
	}
}
           

繼續閱讀