创建父类:
package org.hanqi.pn0120; public class Father { private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} // public Father()
// {
// System.out.println("父类的构造方法");
// }
public Father (String name)
{
System.out.println("父类的有参的构造方法");
this.name = name;
}
//工作
public void work()
{
System.out.println("我劳动我光荣");
}
}
创建子类:
package org.hanqi.pn0120; public class Son extends Father {
//Object a;所有类的父类 public Son()
{
//super 表示父类
super("儿子");
System.out.println("子类的构造方法");
}
public void sing()
{
System.out.println("我喜欢唱歌");
}
//覆盖(重写)
public void work()
{
//调用父类的方法
//super.work();
//System.out.println("我不喜欢上班,我要去参加海选");
System.out.println("我边上班边练歌");
} public static Object getData(int i)
{
Object rtn = null;
//获取数据
if (i==1)
{
//1 father
Father f = new Father("向上转型的父类");
//向上转型
rtn = f;
}
else
{
//2 son
Son s = new Son();
rtn = s;
}
return rtn;
}
}
创建测试类:
package org.hanqi.pn0120; public class TestJiCheng { public static void main(String[] args) {
//
Father f = new Father("父亲");
f.setName("父亲");
f.setAge(50);
System.out.println("名字是:"+f.getName()+" 年龄是:"+f.getAge());
f.work();
Son s = new Son();
s.setName("儿子");
s.setAge(20);
System.out.println("名字是:"+s.getName()+" 年龄是:"+s.getAge());
s.work();
s.sing(); System.out.println(); //转型
//向上转型 子类转成父类
Father f1 = new Son();
System.out.println("名字是:"+s.getName());
f1.work();//如果被子类重写,调用子类的方法
//f1.sing 若父类想调用子类特有的成员,必须再进行向下转型 System.out.println("向下转型");
//向下转型 父类转成子类
//Son s1 = (Son) new Father("父亲");
Son s1 = (Son) f1;
s1.work();
s1.sing();
System.out.println(); Father f2 = (Father)Son.getData(1);
f2.work();
}
}
运行结果为:
总结:
package org.hanqi.pn0120; public class TestZhuanXing { public static void main(String[] args) { // 向上转型
Object obj = new Son();
//判断某个对象是否是某个类的实例,返回boolean
if(obj instanceof Son)
{
System.out.println("obj是Son的实例");
} Father f = new Father(""); if(f instanceof Son)
{
System.out.println("f是Son的实例");
}
else
{
System.out.println("f不是Son的实例");
}
if(obj instanceof Father)
{
System.out.println("boj是Father的实例");
}
else
{
System.out.println("boj不是Father的实例");
} //向下转型
Son s = (Son)obj;
s.work();
s.sing();
Father f1 = (Father)obj;
f1.work();
}
}
运行结果为:
附思维导图: