Java中的多态

本文介绍Java中父类与子类之间的向上转型(upcast)原理及其应用实例。通过具体的代码示例,展示了如何实现从子类到父类的转换,并解释了多态的概念以及Java如何根据对象的真实类型调用相应方法。

父类Human子类Woman

我们可以将一个子类引用转换为其父类引用,这叫做向上转换(upcast)或者宽松转换。下面的Woman类继承自Human类,并覆盖了Human类中原有的breath():

可以看到,不需要任何显示说明,我们将子类引用W赋予给它的父类引用H。类型转换将由Java自动进行。

我们随后调用了W(我们声明它为Human类型的breath()方法。尽管HHuman类型的引用,它实际上调用的是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());
		
		}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值