父类Human子类Woman
我们可以将一个子类引用转换为其父类引用,这叫做向上转换(upcast)或者宽松转换。下面的Woman类继承自Human类,并覆盖了Human类中原有的breath():
可以看到,不需要任何显示说明,我们将子类引用W赋予给它的父类引用H。类型转换将由Java自动进行。
我们随后调用了W(我们声明它为Human类型)的breath()方法。尽管H是Human类型的引用,它实际上调用的是Woman的breath()方法!也就是说,即使我们经过upcast,将引用的类型宽松为其基类,Java依然能正确的识别对象本身的类型,并调用正确的方法。Java可以根据当前状况,识别对象的真实类型,这叫做多态(polymorphism)。多态是面向对象的一个重要方面。
多态是Java的支持的一种机制,同时也是面向对象的一个重要概念。这提出了一个分类学的问题,既子类对象实际上“是”父类对象。比如一只鸟,也是一个动物;一辆汽车,也必然是一个交通工具。Java告诉我们,一个衍生类对象可以当做一个基类对象使用,而Java会正确的处理这种情况。
Human类:
package hello;
import java.util.*;
public class Human
{ public static int population;
public static boolean is_mammal = true;
private int height;
protected int width;
public static int getPopulation()
{
return Human.population;
}
public void breath()
{
System.out.println("hu...hu...hu...");
}
public int getHeight()
{
return this.height ;
}
public void growHeight(int n)
{
this.height+=n;
}
private void repeatBreath(int rep)
{
for(int i = 0;i<rep;i++)
this.breath();
}
Human(int h)
{
this.height = h;
this.width = h/2;
System.out.println("I'm born");
Human.population+=1;
}
Human(int h,String s)
{
this.height = h;
System.out.println("Ne zha:I'm born,"+s);
Human.population+=1;
}
}
Woman类
package hello;
class Woman extends Human
{public int height;
Woman(int h) {
super(h);
// TODO Auto-generated constructor stub
height = h;
}
public Human giveBirth()
{
System.out.println("Given birth");
return (new Human(20));
}
public void breath()
{
System.out.println("su...");
}
public int getwidth()
{
return super.width;
}
public int getHeight()
{
return this.height;
}
}
Test类
package hello;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Scanner sc = new Scanner(System.in);
//
// int m = sc.nextInt();
// String n =sc.next();
// Human apeason =new Human(m,n);
// Human dummyPerson = apeason;
// System.out.println(dummyPerson .getHeight());
// apeason.growHeight(20);
// System.out.println(dummyPerson .getHeight());
// System.out.println(apeason.getHeight());
// apeason.growHeight(10);
// System.out.println(apeason.getHeight());
// //apeason.repeatBreath(4);
// Woman w = new Woman(20);
// w.breath();
// System.out.println(w.width);
// System.out.println(Human.getPopulation());
// System.out.println(apeason.getPopulation());
Human H = new Woman(5);
Woman W = new Woman(6);
H = W;
H.breath();
System.out.println(H.getHeight());
}
}