多态_课后练习
代码阅读分析题
第1题
考核知识点:属性与多态无关
package com.atguigu.test01;
public class Test01 {
public static void main(String[] args) {
A a = new B();
System.out.println(a.num); //num=1
System.out.println(((B)a).num);//num=1
System.out.println(((A) ((B)a)).num);//num=2
System.out.println("-------------------");
B b = new B();
System.out.println(b.num);//2
System.out.println(((A)b).num);//1
System.out.println(((B)((A)b)).num);//2
}
}
class A{
int num = 1;
}
class B extends A{
int num = 2;
}
第2题
考核知识点:实例初始化方法,属性与多态无关
package com.atguigu.test02;
public class Test02 {
public static void main(String[] args) {
Father f = new Son();
System.out.println(f.x);
}
}
class Father{
int x = 10;
public Father(){
this.print();
x = 20;
}
public void print(){
System.out.println("Father.x = " + x);
}
}
class Son extends Father{
int x = 30;
public Son(){
this.print();
x = 40;
}
public void print(){
System.out.println("Son.x = " + x);
}
}
第3题
考核知识点:多态,重写,实例初始化过程
package com.atguigu.test03;
public class Test03 {
public static void main(String[] args) {
Base b1 = new Base();
Base b2 = new Sub();
}
}
class Base {
Base() {
method(100);
}
public void method(int i) {
System.out.println("base : " + i);
}
}
class Sub extends Base {
Sub() {
super.method(70);
}
public void method(int j) {
System.out.println("sub : " + j);
}
}
第4题
考核知识点:多态、重载、重写
public class Test04 {
public static void main(String[] args) {
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println("(1)" + a1.show(b));
System.out.println("(2)" + a2.show(d));
System.out.println("(3)" + b.show(c));
System.out.println("(4)" + b.show(d));
}
}
class A{
public String show(D obj){
return ("A and D");
}
public String show(A obj){
return "A and A";
}
}
class B extends A{
public String show(B obj){
return "B and B";
}
public String show(A obj){
return "B and A";
}
}
class C extends B{
}
class D extends B{
}
第5题
考核知识点:多态、重载、重写
public class Test05 {
public static void main(String[] args) {
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println("(1)" + a1.show(b));
System.out.println("(2)" + a2.show(d));
System.out.println("(3)" + b.show(c));
System.out.println("(4)" + b.show(d));
}
}
class A {
public String show(C obj) {
return ("A and C");
}
public String show(A obj) {
return "A and A";
}
}
class B extends A {
public String show(B obj) {
return "B and B";
}
public String show(A obj) {
return "B and A";
}
}
class C extends B {
}
class D extends B {
}
第6题
考核知识点:属性与多态无关
public class Test06 {
public static void main(String[] args) {
Base b = new Sub();
System.out.println(b.x);
}
}
class Base{
int x = 1;
}
class Sub extends Base{
int x = 2;
}