Java object-oriented inheritance important point

Three characteristics of object-oriented

In order to simplify the use of class organization, further transformation: high cohesion and low coupling

inherit

Continuation and expansion of the parent class information
to add override | rewrite

   延续: 子类没有父类有
   新增: 子类有父类没有
   重写: 子父类都有改写
   
   继承链
       追溯本源
       
   子类实例化
       先静态后成员  先父类后子类

Example subclass instantiation

/**
* 
* new 
* 1、开辟空间+默认值
* 2、初始化
* 	1)、=
* 	2)、构造块
* 	3)、构造器
* 3、返回值
* 
* 
* 存在继承
* 1、父亲的空间+默认值; 子类的空间+默认值
* 2、父类依次初始化 完毕后;子类的依次初始化
* 3、返回地址给引用
* 
* 就近最优: 注意方法是否被重写,
* 如果重写找子类的方法,
* 没有重写找父类的方法
* 
* @author TW
*
*/
public class Parent {
   int a=5 ;
   
   public Parent() {
   	test(); //访问时机 是在构造父类时 ,此时子类没有初始化,使用的都是子类的默认值
   }
   
   public void test() {
   	System.out.println(a);
   }
   
   public static void main(String[] args) {
   	new Child();
   	
   }
}

class Child extends Parent{	
   int a=20;	
   int b=30;
   
   
   public Child() {
   	this.a =10;
   	this.b =20;
   }	
   
   /*
   public void test() {
   	System.out.println(a);
   }*/
   
}

首先父类里的程序入口点main方法里第一行代码,new一个子类,根据子类实例化规则:先静态后成员;先父类后子类,首先在创造子类的时候,必须创建父类,new一个对象会做三件事,开辟空间给默认值,然后初始化,再传地址给引用,然后代码在new的时候首先开辟空间在方法区,有了父类和子类的方法,然后给予默认值,父类中的a=0,子类中的a=0,b=0,然后再进父类初始化,(从=到构造块再到构造器),然后子类初始化(从=到构造块再到构造器),然后new成功。

在第一次调用父类构造器然后调用方法的时候test() 没有重写 ,输出的值为 5,如果存在就是Child开始赋的值了

注意:static块和static变量,谁在最前面先执行谁
   不管静态的方法或者属性是在子类还是父类
   先执行静态的,再去执行成员的

Object

任何一个类的老祖宗就是Object  . Object所有的方法都会被继承下来。

Package

Data protection | social division of labor, access to

Polymorphism

A variety of forms, maintaining the status quo, the code versatility and scalability

Published 13 original articles · won praise 13 · views 495

Guess you like

Origin blog.csdn.net/Rabbit_white_/article/details/104061216