Java inheritance (deepen understanding)

Foreword

Earlier we understand the three characteristics of object-oriented: encapsulation, inheritance, polymorphism.

So in Java is how to show it inherited characteristics? For when the subclass inherits the parent class, what restrictions?

After that answer these questions, we find out about the loading process under class, a better understanding of inheritance.

(Article if there is not correct place, or places difficult to understand, a lot of understanding, please correct me)

The introduction of inheritance

If we have two classes: biology, cats.

Biological categories:

class Animal{
	private String name;
	public void setName(String name){
		this.name = name;
	}
	public String getName(){
		return this.name;
	} 
}

Cats:

class Cat{
	private String name;
    private String sound;
	public void setName(String name){
		this.name = name;
	}
    public void setSound(String sound){
        this.sound = sound;
    }
	public String getName(){
		return this.name;
	} 
    public String getSound(){
        return this.sound;
    }
}

We know that the cat is also a part of organisms, some biological properties and behavior, cats intuitively, is there. But this time there is no concept of inheritance, the code will not reuse , long-term development, code redundancy, maintenance workload difficult and developers is also very large.

The concept of inheritance

Inheritance is the subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) instance fields and methods having a parent class or subclass inherits methods from parent classes, subclasses that have the same parent class behavior.

In simple terms, the subclass can absorb existing parent class attributes and behavior. In addition, subclasses can also expand their capabilities. Subclass is also known as a derived class, parent class is called the superclass.

In Java, if you want to achieve inheritance relationship, you can use the following syntax:

class 子类 extends 父类{}

The basic implementation inheritance

Inherited basically as follows:

class Animal{
	private String name;
	public void setName(String name){
		this.name = name;
	}
	public String getName(){
		return this.name;
	} 
}
class Cat extends Animal{}

public class Test{
    public static void main(String[] args){
        Cat cat = new Cat();
        cat.setName("猫");
        System.out.println(cat.getName());
    }
}

Operating results as follows:

We can see that subclasses can without spreading operation using properties and functions of the parent class .

Expand the subclass the parent class

Inherited basically as follows:

class Animal{
	private String name;
	public void setName(String name){
		this.name = name;
	}
	public String getName(){
		return this.name;
	} 
}
class Cat extends Animal{
    private String sound;
    public void setSound(String sound){
		this.sound = sound;
	}
	public String getSound(){
		return this.sound;
	} 
}

public class Test{
    public static void main(String[] args){
        Cat cat = new Cat();
        cat.setName("NYfor2020")
        cat.setSound("我不是你最爱的小甜甜了吗?");
        System.out.println(cat.getName()+":"+cat.getSound());
    }
}

Operating results as follows:

NYfor2020:我不是你最爱的小甜甜了吗?

We can see that the subclass was extended on the basis of the parent class, but also for the parent class, the scope of the subclass definition is more specific. In other words, the subclass is a means to the parent class of concrete .

In summary, the relationship between the use of the subclass inherits the parent class and Java, can achieve code reuse , subclasses can also extend the functionality according to the needs.

Inherited limit

1. subclass can only inherit a parent class

** Why can not subclass multiple inheritance? ** For chestnuts.

class ACat{
	public void mewo(){...}
}
class BCat{
	public void mewo(){...}
}
class CCat extends ACat, BCat{
	@Override
	public void mewo(){...?}  //提问:这里的mewo()是继承自哪个类?
}

Although Java supports only single inheritance, but not opposed to a multi-layer inherit it!

class ACat{}
class BCat extends ACat{}
class CCat extends BCat{}

In this way, BCat it inherits all the methods ACat, and CCat inherited ACat, BCat all the way, in fact CCat it is ACat child (Sun) class is a subclass of BCat.

In summary, the subclass although does not support multiple inheritance, only single inheritance, but multiple layers can inherit .

2. private modification is not directly accessible, final modification can not be modified

private modification

For subclasses, the parent class with private properties modified its hidden , but if this variable provides setter / getter interfaces, or can access and modify this variable.

class ACat {
    private String sound = "meow";
    public String getSound() {
        return sound;
    }
    public void setSound(String sound) {
        this.sound = sound;
    }
}

class BCat extends ACat {
}

public class Test {
    public static void main(String[] args) {
        BCat b = new BCat();
        b.setSound("我不是你最爱的小甜甜了吗?");
        System.out.println(b.getSound());
    }
}

final modification

Parent class has been defined final modification of variables (method, too), subclasses can access the property (or method), but can not be changed .

class ACat {
    final String sound = "你是我最爱的小甜甜";
    public String getSound() {
        return sound;
    }
    public void setSound(String sound){
        this.sound = sound;  //这句执行不了,会报错的
    }
}

class BCat extends ACat {
}

In summary, with private variables can be modified by operating getter / setter interfaces, final modified variables can only access can not be changed .

The default constructor to call the parent class 3. Examples of subclasses

When an object instance of subclasses, will call the parent class constructor initializes the properties, and then after the call the constructor for the subclass.

class A {
    public A(){
        System.out.println("我不是你最爱的小甜甜了吗?");
    }
    public A(String q){
        System.out.println(q);
    }
}

class B extends A {
    public B(){
        System.out.println("你是个好姑娘");
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
    }
}

Operating results as follows:

我不是你最爱的小甜甜了吗?
你是个好姑娘

From the results we can know, when instantiating subclasses, it will default to call the parent class constructor parameter-free , and then mobilize the constructor for subclasses.

So how to call the parent class constructor with parameters of it? As long as the first line call super subclass constructor () method like.

class A {
    public A(String q){
        System.out.println(q);
    }
}

class B extends A {
    public B(){
        super("我是你的小甜甜?");
        System.out.println("你是个好姑娘");
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
    }
}

Operating results as follows:

我是你的小甜甜?
你是个好姑娘

When the subclass is instantiated, the default calling the constructor with no arguments parent class, and if no parent class constructor with no arguments, the subclass must have reference constructor to call the parent class by super () , and super ( ) method must be the first line in the constructor for subclasses .

To summarize, Java inheritance there are three inherent limitations, which are a subclass only single inheritance, the parent class private variables can not be modified explicitly accessed and modified final variables can not be changed, as well as examples of subclasses sure to first call the parent class construction methods, only after calling the constructor for subclasses.

How the class is loaded?

(Here is a rough introduction class loading process, reference may want to know more "in-depth understanding of the Java Virtual Machine")

Class loading process consists of three major steps: loading the connection initialization .

Start time these three steps remained fixed sequence, but the undertaking and completion schedule is not necessarily in this order a.
Here Insert Picture Description

  1. Loading: the virtual machine the fully qualified name of the class to get the binary byte stream class , then extracts the byte stream configuration data class , and converted to the class in the process operating region (storage class structure) data structure ;
  2. Verify: verify that the byte stream for compliance with Class file format, and then check the parent of this class if there is a conflict of data (e.g., a parent of this class inherit the class is modified final), Next, the intra-class the method of body checking, if no problem, then draw before the symbolic reference into direct reference ;
  3. Preparation: for the class variable (static variables modified) allocates memory (area method) and set the initial value of the class variable , and the initial value here is the zero value of this data type, such as an initial value of int is 0;
  4. Analysis: In the Class file loading process, the method will identify the Class file, constant interface into the constant pool, and these constants for virtual machines, it is symbolic references . This stage is for the classes, interfaces, and other field-based symbolic references 7, converted to the target directly handle - a direct reference .
  5. Initialization: This stage is the implementation of static block of code and class constructor process, a small partner may be wondering is not the default static class constructor do? For more details, please see this blog: Again on the static keyword in Java .

After sum up, the process of loading the class, first class will extract and convert the data structures into the runtime Class file, then the data and information of the parent class of this class tested, to allocate memory for class class variables and set the initial value, then this class class file associated with the symbolic reference into a direct reference, then performing the class constructor.

And we can see from the second step, the loaded class, will go to check the information of the parent class of this class, and then check the method body of this class, that is, at the time the class is loaded, it will go load its parent class .

Epilogue

Java beginners know when these concepts, but just tasted full length. Now follow Hollis Gangster " the Java way engineers to God! "Revisit this knowledge, I found myself just like before, if one-sided understanding, it would mean that there is no growth? So in the process of writing the article, an attempt to write more in-depth and easy to understand as much as possible. Of course, I am limited, if any place is not correct, please correct me.

PS: tutoring kids work really hard, and definitely because of love, my little cousin was tutoring one-hour English homework.

References:

[Java inheritance (extends) Detailed] (

Released six original articles · won praise 0 · Views 158

Guess you like

Origin blog.csdn.net/NYfor2017/article/details/104683774