对象转型
来源:互联网 发布:淘宝同行跳失率怎么看 编辑:程序博客网 时间:2024/05/16 07:46
public class Exe1{public static void main(String[] args){ Person p=new Person(1); Student s1=new Student(12,"john"); p=new Student(12,"nihao"); Student s2=(Student)p;//想调用student新增的属性,强制转换}}class Person{ private int age; private String name; Person(int age) { this.age=age; name="merry"; } Person(int age,String name) { this.age=age; this.name=name; }}class Student extends Person{ private String school; Student(int a,String n,String school) { super(a,n); this.school=school; } Student(int a,String n) { this(a,n,"qinghua"); }}```![这里写图片描述](http://img.blog.csdn.net/20170913084232387?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXhobHk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)<div class="se-preview-section-delimiter"></div>
public class Exe1{
public static void main(String[] args)
{
Animal a=new Animal(“smallwhite”);
Cat cat=new Cat(“smallwhite”,”red”);
System.out.print(a instanceof Animal);
a=new Cat(“smallblack”,”blue”);
// System.out.println(a.eyeColor);err
System.out.println(a.name);
Cat c=(Cat)a;
System.out.println(c.eyeColor);
Exe1 exe=new Exe1();
exe.f(a);
exe.f(cat);//基类对象指向子类对象
}
public void f(Animal a)
{
System.out.println(“name: “+a.name);
}
}
class Animal{
public String name;
Animal(String name)
{
this.name=name;
}
}
class Cat extends Animal{
public String eyeColor;
Cat(String n,String e)
{
super(n);
eyeColor=e;
}
}
“`
一个基类的引用类型变量可以“指向”其子类的对象如: p=new Student(12,”nihao”);
一个基类的引用不可以访问其子类对象新增加的成员(属性和方法)
子类的对象可以当做基类的对象来使用称为向上转型(upcasting),反之称为向下转型
public class Exe1{ public static void main(String[] args) { Animal a=new Animal("smallwhite"); Cat cat=new Cat("smallwhite","red"); System.out.print(a instanceof Animal); a=new Cat("smallblack","blue"); // System.out.println(a.eyeColor);err System.out.println(a.name); Cat c=(Cat)a; System.out.println(c.eyeColor); Exe1 exe=new Exe1(); exe.f(a); exe.f(cat);//基类对象指向子类对象 } public void f(Animal a) { System.out.println("name: "+a.name); }}class Animal{ public String name; Animal(String name) { this.name=name; }}class Cat extends Animal{ public String eyeColor; Cat(String n,String e) { super(n); eyeColor=e; }}
一个基类的引用类型变量可以“指向”其子类的对象如: p=new Student(12,”nihao”);
一个基类的引用不可以访问其子类对象新增加的成员(属性和方法),也即其指向的是内存中子类中的父类
子类的对象可以当做基类的对象来使用称为向上转型(upcasting),反之称为向下转型
- 对象转型
- 对象转型
- 对象转型
- 对象转型
- 对象转型
- 对象转型
- 对象转型 (casting)
- java中的对象转型
- 对象的转型
- 上转型对象
- 关于对象的转型
- 关于对象转型00
- java之上转型对象
- Casting(对象转型)I
- 对象转型小结
- Java之对象转型
- 上转型对象
- Java中的对象转型
- C++控制台程序字符输入总结
- pscoser(PS启动界面修改工具)下载 v1.1官方版
- 提高CI运行速度的简单方法
- Centos软件管理
- SAP Open SQL
- 对象转型
- Android 起始篇
- Windows命令
- 【POJ】1363---Rails(栈)
- Spring Cloud构建微服务架构:服务容错保护
- Qt在pro中实现条件编译
- Spring Cloud构建微服务架构:Hystrix监控面板
- Unity3D_圆环算法
- C++学习笔记(6)-异常处理