java多态性---upcasting and downcasting
2020-11-25 03:40
标签:java 多态性 upcasting downcasting
upcasting之后仅仅对父类的属性和方法可见
java多态性---upcasting and downcasting 标签:java 多态性 upcasting downcasting 原文地址:http://blog.csdn.net/cjc211322/article/details/248001151、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();
}
}
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可见性问题
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();
}
}
改成如下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();
}
}
上一篇:使用WebView中的Javascript和本地代码交互
下一篇:PHP初解
文章标题:java多态性---upcasting and downcasting
文章链接:http://soscw.com/index.php/essay/22564.html