java面向对象特点之一——多态

一.面向对象的四大特征:抽象、继承、封装、多态
二.多态的实现条件:1.继承
     2.重写
     3.向上转型(父类引用指向子类对象)
三.多态的实现方式:1.接口实现
     2.继承父类重写父类方法
     3.同类中方法重写
四、多态理解
父类代码


public class Father {

	public Father() {
		System.out.println("我是父类构造");
	}
	
	public void name() {
		System.out.println("我是父类的name方法");
	}
}

子类代码

public class Son extends Father {

	public Son() {
		System.out.println("我是子类构造");
	}
	
	public void name() {
		System.out.println("我是子类的name方法");
	}
	
	public void age() {
		System.out.println("我是子类的age方法,父类没有");
	}
}

测试代码:这是一个很简单多态的例子,Son继承Father,重写了父类的name方法,在测试代码中,父类引用指向子类对象,调用重写的方法,具体执行的是子类的还是父类的呢,调用子类特有方法呢?我们看下面例子。

public class Test {

	public static void main(String[] args) {
		Father f=new Son();
		f.name();
		Son s=(Son)f;
		s.age();
	}
}

运行结果:
 
总结:
 父类引用不能调用子类特有方法。
将父类引用强转为子类才可以调用子类特有方法
总之正常情况下先走父类构造,再走子类构造,再走子类重写方法
方法重载注意事项:
l    重载方法参数必须不同:
参数个数不同,如method(int x)与method(int x,int y)不同
参数类型不同,如method(int x)与method(double x)不同g
参数顺序不同,如method(int x,double y)与method(double x,int y)不同
l   重载只与方法名与参数类型相关与返回值无关
如void method(int x)与int method(int y)不是方法重载,不能同时存在
l    重载与具体的变量标识符无关
五、笔试题                                                                                                                                                                                 

 public class A {
    public String show(D obj) {
        return ("A and D");
    }

    public String show(A obj) {
        return ("A and A");
    } 

}

public class B extends A{
    public String show(B obj){
        return ("B and B");
    }
    
    public String show(A obj){
        return ("B and A");
    } 
}

public class C extends B{

}

public class D extends B{

}

public class Test {
    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--" + a1.show(c));
        System.out.println("3--" + a1.show(d));
        System.out.println("4--" + a2.show(b));
        System.out.println("5--" + a2.show(c));
        System.out.println("6--" + a2.show(d));
        System.out.println("7--" + b.show(b));
        System.out.println("8--" + b.show(c));
        System.out.println("9--" + b.show(d));      
    }
}

运行结果:
 
其实在继承链中对象方法的调用存在一个优先级:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。
问题关键的两点:1.子类可以当做父类来使用
2.子类对象当做父类来使用时就失去了子类特性,只能保留与父类同名的属性与方法
1)A类中不存在该方法,是参数中有多态的情况
2) 同上
3) 存在该方法,直接调用的情况。
4) 父类引用指向子类对象,失去了子类特性的情况,调用同名的方法,同名方法参数存在多态的情况。
5) 同上
6)子类不存在该方法,父类存在的情况下,直接调用父类的方法
7) 子类中存在该方法,直接调用。
8) 子类父类都不存在该方法,子类方法参数存在多态情况。服从继承链中对象方法调用优先级
 9) 父类存在该方法,调用父类方法

猜你喜欢

转载自blog.csdn.net/qq_36897901/article/details/91481445
今日推荐