---
title: "[原创]java中的向上转型与方法调用"
author: "JustT0"
date: "2013-11-14T22:50:16Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-11-14T22:50:16Z"
id: 1974928
url: "https://justt0.iteye.com/blog/1974928"
---

java中的向上转型，如Shape shape = new Triangle(); 不是说把创建好的的Triangle对象“转化”成一个java对象，而是缩小该对象可被调用的方法，只可以调用和父类相同的方法即父类的全部方法，相当于“变成”了一个父类对象，下列例子描述了一个Shape类和他的子类Triangle，父类包含两个方法，say()和hello()，say()方法调用hello方法;子类重写了父类的hello方法，say()方法没有改动。

父类Shape

```
package com.wm;

public class Shape {
	public void say() {
		hello();//相当于this.hello(); 而this指的就是当前对象
	}

	protected void hello() {
		System.out.println("Hello Shape");
	}
}
```

 子类Triangle

```
package com.x;

import com.wm.Shape;

public class Triangle extends Shape {

	public static void main(String[] args) {
		Triangle triangle = new Triangle();
		System.out.println(triangle);
		Shape shape = triangle;
		System.out.println(triangle);
		shape.say();
	}

	@Override
	protected void hello() {
		// TODO Auto-generated method stub
		System.out.println("hello Triangle");
	}
}
```

运行结果是：

com.x.Triangle@f72e77

com.x.Triangle@f72e77

hello Triangle

通过结果可知，虽然把Triangle对象向上转型为Shape对象，但是对象的类型并没有改变，还是com.x.Triangle，所以，在子类中调用say()方法调用的hello()方法就是子类中被覆盖的hello()方法。