java多态性---upcasting and 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();	
	}
}


java多态性---upcasting and downcasting_第1张图片

java多态性---upcasting and downcasting_第2张图片


java多态性---upcasting and downcasting_第3张图片

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


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();	
	}
}

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();
	}
}
java多态性---upcasting and downcasting_第4张图片
改成如下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();
	}
}


你可能感兴趣的:(java,upcasting,downcasting,多态性)