java多态性---upcasting and downcasting

2020-11-25 03:40

阅读:745

标签:java   多态性   upcasting   downcasting   

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,搜素材

java多态性---upcasting and downcasting

标签:java   多态性   upcasting   downcasting   

原文地址:http://blog.csdn.net/cjc211322/article/details/24800115


评论


亲,登录后才可以留言!