import java.util.Scanner;
//多态中;编译看最左边,运行看右边(向上转型,向下转型)
class Test {
public static void main(String[] args) {
System.out.println("hello world !!! "); //多态的使用,直接以对象当做参数传入,要想使用单个对象的特需方法,可以强转调用
method(new Cat());
method(new Dog());
}
public static void method (Animal a) {
a.eat();
}
}
class Animal {
public void eat() {
System.out.println(" Animal eat some foods !!! ");
}
}
class Cat extends Animal {
public void eat() {
System.out.println(" Cat eats fish");
}
public void catchMouse() {
System.out.println(" Catch Mouse");
}
}
class Dog extends Animal {
public void eat() {
System.out.println(" Dog eats meat");
}
public void lookHome() {
System.out.println(" look Home");
}
}
//多态例子
class Test {
public static void main(String[] args) {
Person p = new SuperMan();
System.out.println(p.name); // join
p.talk(); //superman talk with someone for one million
Superman t = (SuperMan)p; //强转,需要先做个向上转型
t.fly();
}
}
class Person {
String name = "John";
public void talk (){
System.out.println(" join talk with someone ... ");
}
}
class SuperMan extends Person {
String name = "SuperMan";
public void talk (){
System.out.println("superman talk with someone for one million ... ");
}
public void fly (){
System.out.println("talk with someone for one million ... ");
}
}
java-forced conversion type
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Failed to convert from type [java.lang.String] to type [l...
- 问题背景(可以选择性跳过直接看结论-。-) 最近换了一个Eclipse,在写代码的时候发现代码提示有问题,比如想打...