本文主要是介绍java多态巩固,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
多态巩固代码阅读题
目录
多态巩固代码阅读题
(1)阅读如下代码,分析运行结果
(2)阅读如下代码,分析运行结果
(3)阅读如下代码,分析运行结果
(4)阅读如下代码,分析运行结果
(5)阅读如下代码,分析运行结果
(1)阅读如下代码,分析运行结果
public class Test01 {public static void main(String[] args) {A a = new B();System.out.println(a.num);System.out.println(((B)a).num);System.out.println(((A)((B)a)).num);System.out.println("-------------------");B b = new B();System.out.println(b.num);System.out.println(((A)b).num);System.out.println(((B)((A)b)).num);}
}
class A{int num = 1;
}
class B extends A{int num = 2;
}
(2)阅读如下代码,分析运行结果
public class Test2 {public static void main(String[] args) {Father f = new Father();Father s = new Son();Father d = new Daughter();
MyClass my = new MyClass();my.method(f);my.method(s);my.method(d);}
}
class MyClass{public void method(Father f) {System.out.println("father");}public void method(Son s) {System.out.println("son");}public void method(Daughter f) {System.out.println("daughter");}
}
class Father{}
class Son extends Father{}
class Daughter extends Father{}
(3)阅读如下代码,分析运行结果
public class Test3 {public static void main(String[] args) {MyClass my = new MyClass();Father f = new Father();Son s = new Son();Daughter d = new Daughter();my.method(f);my.method(s);my.method(d);}
}
class MyClass{public void method(Father f) {System.out.println("father");}public void method(Son s) {System.out.println("son");}
}
class Father{}
class Son extends Father{}
class Daughter extends Father{}
(4)阅读如下代码,分析运行结果
public class Test4 {public static void main(String[] args) {MyClass my = new MySub();Father f = new Father();Son s = new Son();Daughter d = new Daughter();my.method(f);my.method(s);my.method(d);}
}
class MyClass{public void method(Father f) {System.out.println("father");}public void method(Son s) {System.out.println("son");}
}
class MySub extends MyClass{public void method(Daughter d) {System.out.println("daughter");}
}
class Father{}
class Son extends Father{}
class Daughter extends Father{}
(5)阅读如下代码,分析运行结果
public class Test5 {public static void main(String[] args) {MyClass my = new MySub();Father f = new Father();Son s = new Son();Daughter d = new Daughter();my.method(f);my.method(s);my.method(d);}
}
class MyClass{public void method(Father f) {System.out.println("father");}public void method(Son s) {System.out.println("son");}
}
class MySub extends MyClass{public void method(Father d) {System.out.println("daughter");}
}
class Father{
}
class Son extends Father{
}
class Daughter extends Father{}
这篇关于java多态巩固的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!