java多态性---upcasting and downcasting

时间:2014-04-30 22:33:38   收藏:0   阅读:232

1、upcasting和downcasting

class Person
{
	void fun1()
	{
		System.out.println("Person‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Person‘s fun2");	
	}
}
class Student extends Person
{
	Student()
	{
	
	}
	void fun1()
	{
		System.out.println("Student‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Student‘s fun2");	
	}	
}
public class JavaTest
{
	public static void	main(String[] agrs)
	{
		Person p=new Student();
		p.fun1();
		p.fun2();	
	}
}


mamicode.com,码迷

mamicode.com,码迷

mamicode.com,码迷

mamicode.com,码迷

2、强制类型转换需要注意的问题

mamicode.com,码迷

class Person
{
	void fun1()
	{
		System.out.println("Person‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Person‘s fun2");	
	}
}
class Student extends Person
{
	void fun1()
	{
		System.out.println("Student‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Student‘s fun2");	
	}	
}
public class JavaTest
{
	public static void main(String[] agrs)
	{
		Person p=new Person();
		Student stu=(Student)p;
		stu.fun1();
		stu.fun2();	
	}
}
mamicode.com,码迷

3、casting可见性问题

upcasting之后仅仅对父类的属性和方法可见

class Person
{
	void fun1()
	{
		System.out.println("Person‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Person‘s fun2");	
	}
}
class Student extends Person
{
	void fun1()
	{
		System.out.println("Student‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Student‘s fun2");	
	}	
	void fun3()
	{
		System.out.println("Student‘s fun3");
	}
}
public class JavaTest
{
	public static void main(String[] agrs)
	{
		Person p=new Student();
		p.fun3();
		Student stu=(Student)p;
		stu.fun3();
	}
}
mamicode.com,码迷
改成如下code即可

class Person
{
	void fun1()
	{
		System.out.println("Person‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Person‘s fun2");	
	}
}
class Student extends Person
{
	void fun1()
	{
		System.out.println("Student‘s fun1");	
	}
	void fun2()
	{
		System.out.println("Student‘s fun2");	
	}	
	void fun3()
	{
		System.out.println("Student‘s fun3");
	}
}
public class JavaTest
{
	public static void main(String[] agrs)
	{
		Person p=new Student();		//upcasting,此时p对fun3不可见
		//p.fun3();
		Student stu=(Student)p;		//downcasting,此时stu对fun3可见
		stu.fun3();
	}
}
mamicode.com,码迷

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!