inheritance

Implementation of inheritance

Inheritance is implemented through extends

Extends extends extends parent {}

Class Dog extends Animal {}

 

The benefits of inheritance

Inheritance allows classes to have relationships with each other, with children and parents, and then subclasses can use non-private members of the parent class.

Public class Fu {public void show() {system.out.println ("show method called "); }} public class extends Fu {public void method() {system.out.println ("method method is called "); }} public class Demo {public static void main(String[] args) {f = new Fu(); f.show(); Zi z = new Zi(); z.method(); z.show(); }}Copy the code

Advantages and disadvantages of inheritance

Inheritance benefits

Improved code reuse (multiple members of the same class can be placed in the same class) improved code maintenance (if the method code needs to be changed, just one change) inheritance drawbacks

 

Inheritance creates relationships between classes, increasing the coupling of classes, and weakening the independence of subclasses when the parent class changes

 

Application scenarios of inheritance:

With inheritance, you need to consider whether there is is between classes. A relation, cannot blindly use inheritance is.. The relation of A: who is one kind of whom, for example: teacher and student are one kind of person, that person is the parent class, student and teacher are the subclass

Features of inheritance in Java

1. Java classes only support single inheritance, not multiple inheritance

Class A extends B, C {}

2. Classes in Java support multiple layers of inheritance

 

Sample code for multi-level inheritance

Public class Granddad {public void drink() {system.out.println (" Granddad likes drinking "); }} public class extends Granddad {public void smoke() {system.out.println (" Father likes smoking "); }} public class Mother {public void dance() {system.out.println (" Mother love to dance "); }} public class extends Father {// Son extends Father;Copy the code

Member access characteristics in inheritance

The access characteristics of variables in inheritance

Access a variable in a subclass method using the proximity principle.

  1. Subclass local scope search
  2. Subclass member scope find
  3. Parent member scope search
  4. If none is present, report an error.
class Fu { int num = 10; } class Zi { int num = 20; public void show(){ int num = 30; System.out.println(num); } } public class Demo1 { public static void main(String[] args) { Zi z = new Zi(); z.show(); // print the local variable in the show method 30}}Copy the code

super

This&super keywords:

This: represents a reference to an object of this class

Super: An identifier representing the storage space of the parent class (understood as a reference to the parent object)

 

Use the member variables for this and super respectively:

This. Member variable – Accesses member variables of the class

Super. Member variables – Access parent class member variables

 

Member methods:

This. Member methods – Access member methods of this class

Super. Member methods – Access parent member methods

 

Construction method:

This (…). – Access this class constructor

Super (…). – Access the parent class constructor

Access characteristics of constructors in inheritance

Note: By default, all constructors in a subclass access the constructor with no arguments in the parent class

Subclasses inherit and possibly use data from their parent class. Therefore, it is important to initialize the data of the parent class before a subclass is initialized. The reason is that the first statement of every subclass constructor defaults to super().

Question: What if there are no no-parameter constructors in the parent class, only parameterized constructors?

1. Call the parameter constructor of the parent class by using the super keyword to display it

2. Subclasses use this to call other constructors of the class, and the other constructors of the class use super to manually call the parameterized constructor of their parent class

Note: this (…). Super (…). Must be in the constructor’s first line of a valid statement, and the two cannot coexist

Access characteristics of member methods in inheritance

Access a method through a subclass object

1. Subclass member scope search

2. Search for the parent member scope

3. If none is present, report an error (not considering the father’s father…)

Methods to rewrite

1. Method rewrite concept

The subclass has exactly the same method declaration as the parent class (the method name must be the same, and the argument list must be the same)

 

2. Application scenarios of method rewriting

When a subclass needs the functionality of its parent class, and the body subclass has its own content, it can override methods in the parent class. In this way, it inherits the functionality of the parent class and defines subclass-specific content

 

Override annotation

Check to see if the current method is overridden

Method rewrite considerations

1. Private methods cannot be overridden (private parent member subclasses cannot inherit)

2. Subclass methods cannot have lower access permissions (public > Default > Private)

3. Static methods cannot be overridden. If a subclass has the same method, it is not overriding the parent class’s method

Public class Fu {private void show() {system.out.println ("Fu show() method is called "); } void method() {system.out.println (" method() method is called "); }} public class Zi extends Fu {/* */ @override private void show() {system.out.println ("Zi in show() method called "); } /* Override private void method() {system.out.println (" method() in Zi is called "); } /* Override public void method() {system.out.println (" method() called ");} /* Override public void method() {system.out.println (" method() called "); }}Copy the code

Permission modifier

Super memory map

An object has a separate super section in the heap to store the data of its parent class (the null argument constructor of the parent class must write).

The parent class has no empty parameter construction

1. Call the parent class argument constructor in a subclass by super

public Child(int age){
        super(age);
        this.age=age;
        System.out.println("Child parameter constructor called");
}
Copy the code

2. Subclasses use this to call other constructors of the class, and the other constructors of the class call super to manually call the parent class with arguments

 

    public Child(){
        this(10);
        System.out.println("Child non_parameter constructor called");
    }
    public Child(int age){
        super(age);
        System.out.println("Child parameter constructor called");
    }
Copy the code

Note that both this and super must be placed on the first constructor line to be a valid statement, and that they cannot coexist

An abstract class

An overview of abstract classes

When we do subclass common function extraction, some methods are not embodied in the parent class, this time we need abstract class!

In Java, a method without a method body should be defined as an abstract method, and a class with an abstract method must be defined as an abstract class!

Abstract class characteristics

Abstract classes and abstract methods must be decorated with the abstract keyword

Public abstract class name {} public abstract void eat();Copy the code

An abstract class does not necessarily have abstract methods, but a class with abstract methods must be an abstract class

Abstract classes cannot be instantiated

Abstract classes can have constructors

A subclass of an abstract class can either override all the abstract methods in the abstract class or become an abstract class itself

Examples of abstract classes

Case needs

Define Cat and Dog.

A cat eats fish. A cat eats fish.

Dog member method: Eat meat, drink…

Implementation steps

1. There are common contents between cats and dogs, so one Animal should be extracted upward.

2. In the parent class Animal, it is impossible to describe the specific implementation of EAT method clearly, so it is defined as an abstract method

3. Abstract methods need to live in an abstract class

4. Let Cat and Dog inherit from Animal. Rewrite eat

5. Create Cat and Dog objects in the test class and call the method test

 

animal

Public void drink(){system.out.println (" drink "); } public Animal(){ } public abstract void eat(); }Copy the code

cats

Public class Cat extends Animal {@override public void eat() {system.out.println (" Cat eats fish "); }}Copy the code

Dogs.

Public class Dog extends Animal {@override public void eat() {system.out.println (" Dog eats meat "); }}Copy the code

The test class

public static void main(String[] args) { Dog d = new Dog(); d.eat(); d.drink(); Cat c = new Cat(); c.drink(); c.eat(); //Animal a = new Animal(); // an abstract class cannot instantiate a call object // a.at (); }Copy the code

Template design pattern

Design patterns

Design pattern is a set of repeatedly used, most people know, cataloged code Design experience summary. Design patterns are used to make code reusable, to make it easier for others to understand, to ensure code reliability, and program reuse.

 

Template design pattern

The abstract class as a whole can be viewed as a template. The things that cannot be determined in the template can be defined as abstract methods, allowing classes that use the template (classes that inherit from the abstract class) to override the abstract method implementation requirements

Advantages of the template design pattern

The template already defines the generic structure, and the user only needs to care about the functionality he or she needs to implement

 

The sample code

Template class

/* CompositionTemplate {public final void write(){system.out.println ("<< my dad >>"); body(); System.out.println(" Ah ~ this is my father "); } public abstract void body(); }Copy the code

The implementation class a.

 

Public class Tom extends CompositionTemplate {@override public void body() {system.out.println (" "+" The other day my dad picked me up from school by bike, and my foot got stuck in the chain of my bike. Dad couldn't move, so he got up and pedaled..." ); }}Copy the code

The test class

public class Test { public static void main(String[] args) { Tom t = new Tom(); t.write(); }}Copy the code

fi nal

fianl the role of the keyword

final represents the ultimate meaning and can be used to modify member methods, member variables, and class final modifies the effects of classes, methods and variables

 

fianl modified classes: a class that cannot be inherited (cannot have subclasses, but can have a parent class)

public final class Parent{};
Copy the code

final modification method: This method cannot be overridden

public final void show{};
Copy the code

final modified variable: indicates that the variable is a constant and cannot be reassigned. Variables are primitive types and cannot change their value

final int a=10; / / a = 20 right; / / errorCopy the code

Variables are reference types. The address value cannot be changed, but the contents of the address can be changed

public static void main(String[] args){ final Student s = new Student(23); s = new Student(24); / / wrong s.s etAge (24); / / is it}Copy the code

The code block

Code Block Overview

In Java, code enclosed in {} is called a code block

Code block classification

Local code block

Location: defined in a method

Role: limit the life cycle of variables, early release, improve memory utilization

Public class Test {/* Local code block position: */ public static void main(String[] args) {{int a = 10; System.out.println(a); } // System.out.println(a); }}Copy the code

Construct code block

Location: outside method definition in a class

Features: Every time the constructor is executed, the code in the code block is executed, and before the constructor is executed, the same code in multiple constructors is extracted into the constructor code block to improve the reuse of the code

Copy the code

public static void main(String[] args) {

Student stu1 = new Student();

Student stu2 = new Student(10);

}

Class Student {{system.out.println (" learn "); class Student {{system.out.println (" learn "); } public Student(){system.out.println (" null argument constructor "); } public Student(int a){system.out.println (" with argument constructor "); }}Copy the code

Output:

study hardCopy the code
Null parameter constructorCopy the code
study hardCopy the code
Constructor with parametersCopy the code

Static code block

Location: outside method definition in a class

The static keyword is used to load the class as it is loaded, and performs only once: some data initialization at class load time

Copy the code
public static void main(String[] args) { Person p1 = new Person(); Person p2 = new Person(10); } class Person {static {system.out.println (" I am a static code block, I executed "); } public Person(){system.out.println (" I am the Person class empty argument constructor "); } public Person(int a){system.out.println (" I am the Person constructor "); }}Copy the code
Copy the code

Output:

I'm a static block of code, and I executeCopy the code
I'm the empty parameter constructor for the Person classCopy the code
I'm the parameterized constructor of the Person classCopy the code
 
Copy the code