2021-01-07

组合与继承

原文链 id="向上转型">向上转型

class Instrument { public void play() {		System.out.println("Instrument.play()"); } }public class Wind extends Instrument {	public void play() {		System.out.println("Wind.play()"); }}public class Music {		public static void tune(Instrument i){		i.play();	}	public static void main(String[] args) {  Wind flute = new Wind();  Music.tune(flute); // 向上转型 }}

从一个更具体的类型转化为更一般的类型,所以向上转型用挂失安全的。子类可能会比父类包含更多的方法,必须至少具有和父类一样的方法。

final

final方法

final方法的作用是防止子类通过重写改变方法的行为
类中所有的private方法都是隐式的指定为final,因为不能访问private方法,所以不能重写它。给private方法加上final修饰并不会给方法带来额外的含义。重写一个private方法时编译并不会报错,一个方法是private的,他就不属于父类的一部分,只是创建了一个同名的方法而已

final类

final类的作用是该类不允许被继承

多态

方法绑定

对于上述向上转型的例子,编译器如何知道该调用哪个方法,方法的入参只是一个Instrument引用
java采用后期绑定,在运行时根据对象的类型进行绑定,在运行时判断对象的类型,从而调用方法,在编译时编译器不知道对象的类型,java对于static和final方法无法采用后期绑定(private方法也是隐式的final)

多态的陷阱

注:多态只是针对于普通方法,对于属性和静态方法不会存在多态
属性在编译时就会被解析

public class Parent { public int field = 0; public int getField(){  return field; }}public class Child extends Parent { public int field = 1; @Override public int getField(){  return field; }}public class TestField { public static void main(String[] args) {  Parent parent = new Child();  System.out.println("parent.field= "+parent.field);  System.out.println("parent.getField= "+parent.getField());  Child child = new Child();  System.out.println("child.field= "+child.field);  System.out.println("child.getField= "+child.getField()); }}

执行结果

parent.field= 0parent.getField= 1child.field= 1child.getField= 1

Parent.field和Child。field被分配了不同的存储空间,Child其实是存在两个filed属性的:本身的以及父类的,但是在引用Child的field的时候,默认的field属性是来自于本身的,如果要获取父类的该属性,需要使用super.field来显示地指定获取父类属性
但是这种情况一般不会发生,首先属性一般来说都是私有private的,其次子类和父类一般也不会起相同的属性名字

对于静态方法的话,静态方法只与类关联,与对象无关

由于本身的博客百度没有收录,博客地 />






原文转载:http://www.shaoqun.com/a/506076.html

跨境电商:https://www.ikjzd.com/

gtc:https://www.ikjzd.com/w/974

萌店:https://www.ikjzd.com/w/1538


原文链id="向上转型">向上转型classInstrument{publicvoidplay(){ System.out.println("Instrument.play()");}}publicclassWindextendsInstrument{ publicvoidplay(){ System.out.println("Wind.
e淘网:e淘网
海淘贝:海淘贝
在岸、离岸人民币对美元汇率双双升破6.90关口!:在岸、离岸人民币对美元汇率双双升破6.90关口!
【马来西亚旅游地点】--马来西亚旅游都去哪好:【马来西亚旅游地点】--马来西亚旅游都去哪好
沙头角口岸坐什么车去大鹏所城?:沙头角口岸坐什么车去大鹏所城?

No comments:

Post a Comment