package com.test; public class Animal { public int age = 1; public void eat() { System.out.println("动物具有吃东西的能力"); } }
package com.test; public class Cat extends Animal{ public int age = 2; public void eat() { System.out.println("兔子吃胡萝卜"); } public void nature() { System.out.println("兔子胆小"); } }
package com.test; public class Initail { public static void main(String[] args) { Animal animal = new Animal(); Animal cat = new Cat(); //Cat cat1 = new Animal();错误 animal.eat(); cat.eat(); //cat.nature();错误 } }
package com.test; public class Initail { public static void main(String[] args) { Dog dog = new Dog(); Animal animal = dog;//向上类型转换 if (animal instanceof Dog) { Dog dog2 = (Dog)animal; } else { System.out.println("无法转换为Dog类型"); } if (animal instanceof Cat) { Cat cat = (Cat)animal; } else { System.out.println("无法转换为Cat类型"); } } }
Dog类和Cat类都继承Animal类
执行结果:
无法转换为Cat类型
package cn.test; public abstract class Telephone { public abstract void call(); public abstract void sendMsg(); }
package cn.test; public class Cellphone extends Telephone { public void call() { System.out.println("用键盘打电话"); } public void sendMsg() { System.out.println("用键盘发短信"); } }
package cn.test; public class Smartphone extends Telephone { @Override public void call() { System.out.println("用语音打电话"); } @Override public void sendMsg() { System.out.println("用语音发短信"); } }
package cn.test; public class Initail { public static void main(String[] args) { Telephone phone1 = new Cellphone(); phone1.call(); Telephone phone2 = new Smartphone(); phone2.call(); } }
执行结果:
用键盘打电话
用语音打电话
package cn.test; public abstract interface IPlayGame { public abstract void playGame(); public static final int NUM = 12; }
package cn.test; public class Psp implements IPlayGame { @Override public void playGame() { System.out.println("游戏机能够打游戏"); } }
package cn.test; public class Initail { public static void main(String[] args) { IPlayGame iplay2 = new Psp(); iplay2.playGame(); System.out.println(Psp.NUM); } }
执行结果:
游戏机能够打游戏
12
原文:http://www.cnblogs.com/tianxintian22/p/6536523.html