java多态性---upcasting and downcasting
2020-11-25 03:40
阅读:845
标签: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();
}
}
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(); } }

改成如下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 and downcasting
标签:java 多态性 upcasting downcasting
原文地址:http://blog.csdn.net/cjc211322/article/details/24800115
上一篇:使用WebView中的Javascript和本地代码交互
下一篇:PHP初解
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:java多态性---upcasting and downcasting
文章链接:http://soscw.com/essay/22564.html
文章标题:java多态性---upcasting and downcasting
文章链接:http://soscw.com/essay/22564.html
评论
亲,登录后才可以留言!