Java Object-Oriented - Inheritance

1. Overview of inheritance

Refers to the previous style, cultural, intellectual, property, etc. come to accept

java Inheritance

Produce parent-child relationship between class and class make

Inherited class is called the parent class (base class, superclass)

Inherited class is called a subclass (derived class)

Format (extends)

{parent class

//.....

}

subclass extends parent class {

//.....

}

What effect after the subclass inherits the parent class

Subclasses may use the parent class nonproprietary member (member variables, members of the method)

example:

// define the parent class the Parent 
public class the Parent { 

    // member variables 
    Private String name; 
    Private int Age; 

    // public access methods 
    // shortcuts: alt + insert quickly create getXXX (), setXXX () and the constructor 

    public void setName (String name) { 
        this.name = name; 
    } 

    public String getName () { 
        return name; 
    } 

    public void the setAge (int Age) { 
        this.age = Age; 
    } 

    public int getAge () { 
        return Age; 
    } 

    // configuration method 

    // constructor with no arguments 
    public the Parent () { 

    } 

    // All parameters configured  
    public Parent (String name, int age ) {
        this.name = name; 
        this.age = Age;
    }
}

 

// define a subclass inherits the parent class Child the Parent 
public class the extends the Parent Child { 

}

 

// test class 
public class the Test { 
    // main function is the main entry to the program, all the code starts here 
    public static void main (String [] args) { 
        //. 1. Create a subclass object 
        Child child = new Child (); 

        . 2 // object to the member variable assignment 
        child.setName ( "Joe Smith"); 
        child.setAge (12); 


        // print 3 object member variable. 
        System.out.println ( "name:" + child.getName () + "Age:" + child.getAge ()); 

        / * 
            subclass can use a non-parent class private member (member variables, members of the method) 
         * / 



    } 
}

 

operation result:

 

 

 

2. The use of inheritance scene

• When multiple classes exist then the same attributes and behavior, these contents can be extracted into a new class, so these classes and new classes produce parent-child relationships, achieve code reuse

Example: Define inheritance and use of animal

Requirements: define classes Dog, Pig class, they share attributes: name, age, sex, common behavior: eat (), especially when the two acts: watch (), snore ()

 

// define a parent class Animal Animal class 
public class Animal { 
    // member variables 
    // Name 
    Private String name; 
    // Age 
    Private int Age; 
    // Sex 
    Private Sex String; 

    // member method 
    // eat conduct 
    public void eat ( ) { 
        System.out.println (this.name + "is eating ...."); 
    } 
    // common access method 


    public void the setName (String name) { 
        this.name = name; 
    } 

    public void the setAge (int Age) { 
        Age = this.age; 
    } 

    public void setSex (String Sex) { 
        this.sex Sex =; 
    } 

    public String getName () {  
        return name;
    }

    int getAge public () { 
        return Age; 
    } 

    public String getSex () { 
        return Sex; 
    } 

    // constructor 

    // constructor with no arguments 
    public Animal () { 

    } 

    // All Parameters configured 
    public Animal (String name, int age , String Sex) { 
        this.name = name; 
        this.age = Age; 
        this.sex Sex =; 
    } 
}

 

// define a subclass inherits the parent class Dog Animal 
public class Dog the extends Animal { 
    // member methods 
    public void Watch () { 
        System.out.println (this.getName () + "is housekeeping"); 
    } 
}

 

// define a subclass inherits the parent class Pig Animal 
public class the extends Pig Animal { // member methods public void SNORE () { System.out.println (this.getName () + "is snoring"); } }

 

// test class 
public class the Test { 
    public static void main (String [] args) { 
        .. 1 // create an object class Dog 
        Dog Dog dog new new = (); 

        . // 2 dog object members subject to assignment 
        dog.setName ( "Husky"); 

        // 3 member variable print dog object. 
        System.out.println ( "name:" + dog.getName ()); 

        . 4 // call the dog object methods 
        dog.eat (); 
        dog .watch (); 

        System.out.println ( "============"); 

        .. 1 // create an object class of a pig 
        Pig Pig pig new new = (); 

        // to 2. pig object member variable assignment 
        pig.setName ( "guinea pig"); 

        // 3 Print pig object member variables. 
        System.out.println ( "name:" + pig.getName ());

        // Call pig member method object  
        pig.eat ();
        pig.snore ();

    }
}

 

operation result:

 

 

3. inherit advantages and disadvantages

advantage:

1. multiplexing function

Directly to the existing properties and behavior inherited realize the multiplexing function, saving a lot of work

2. Easy to develop new features

On the basis of the existing features on easier to build, expand new features

3. A clear structure, simplify understanding

A class inherits attributes associated with the system, they clearly direct structural level, to simplify people's understanding of the code structure

4. Easy to maintain

Inheritance relationships between different classes, so that these maintain a certain degree of consistency between things, greatly reducing maintenance costs

Disadvantages:

1. break encapsulation

Exposing the parent class implementation details of the subclass, breaking the encapsulation of the parent class object

2. High coupling

Tight binding between classes together, high interdependence

The pursuit of program design

Low coupling, high internal poly

- Coupling: two (or more) modules interdependent on each other

- cohesion: the compact module internal structure, strong independence

4. The use of class inheritance members

1. Use of inheritance in the parent class member variables

The difference between this and super

this

- nature: Object

- Usage: This class begins looking for

super

- essence: identifying the parent class memory space

- Usage: start looking from the parent class

example

Requirements: child-parent class defines member variables of the same name, if you are using?

analysis:

A: define the subclass member variable int price, the default value is 10

B: defined in the parent class member variable int price, the default value is 20

C: The method subclass members define local variables int price, the default value is 5

D: price of each output value of the three members of the subclass method

 

// definition of fruit Fruit parent class 
public class Fruit { 
    // member variables 
    // Price 
    int. Price = 20 is; 
}

 

// define a subclass of Apple iPod class 
public class the extends Apple Fruit { 
    // member variables 
    // Price 
    Private int. Price = 10; 

    // member methods 
    public void showPrice () { 

        int =. 5. Price; 
        System.out.println (. Price ); // local variables. 5. price 
        System.out.println (this.price); // subclass members 10 variable. price 
        System.out.println (super.price); // parent member 20 is variable. price 
    } 

}

 

// test class 
public class the Test { 
    public static void main (String [] args) { 
        // test inheritance, a member variable between sub parent 

        // 1. create a subclass object class object apple 
        Apple apple = the Apple new new (); 

        . 2 // call the object methods 
        apple.showPrice (); 

        / * 
            the Java variables used in the rules, follow the principle of proximity 
            local areas have to use, no member of this class went to find a position 
            there to use, no went to the location of the parent class members find 
            there is on the use, not on the error 
         * / 


    } 
}

 

operation result:

 

 

Neutron parent class member method 2. inheritance

example

Requirements: child-parent class defines members of the methods of the same name, how to use

The definition of martial arts class Martial:

Practicing internal strength: internalStrength ()

Exercise moves: stroke ()

Human resource configurations defined class NineYin:

Practicing internal strength: internalStrength ()

Exercise moves: stroke ()

Human resource configurations practice, not only to practice basic internal strength needed softness, need to extend the method of the parent class

Simple moves has been insufficient unused, there must be such a big move 九阴白骨爪 can use, need to re-implement the method in the parent class

// definition of a parent class Martial arts 
public class Martial { 
    // member methods 
    // internal strength practice 
    public void internalStrength () { 
        System.out.println ( "Practice Strength"); 
    } 
    // practice moves 
    public void stroke () { 
        System.out.println ( "exercise moves"); 
    } 
}

 

// define a subclass NineYin human resource configurations class inherits the parent class Martial martial arts class 
public class NineYin the extends Martial { 
    // member method 
    // internal strength exercises 
    public void internalStrength () { 
        // call the parent class members in 
        super.internalStrength (); 

        System.out.println ( "exercise softness"); 

    } 

    public void Stroke () { 
        System.out.println ( "exercise九阴白骨爪"); 
    } 
}

 

// test class 
public class the Test { 
    public static void main (String [] args) { 
        // requirements: the calling method NineYin 
        NineYin nineYin new new NineYin = (); 
        nineYin.internalStrength (); 
        nineYin.stroke (); 
    } 
}

 

 

operation result:

 

 

in conclusion:

1. Find a method of principles:

The principle of proximity

2. Find sequential method

This type -> parent -> higher parent .... Object

3. Access method of the parent class way

super. parent class method name ()

4. The method of the same name defined premise

Wan parent function can not really meet the implementation requirements, extend the parent class functions

Parent class functions are obsolete reimplement the parent class method

Use the constructor of the parent class neutron 3. inheritance

Requirements: When you create an object, how when the constructor is called?

analysis:

A: the definition of the parent class Person, the output statement in the default constructor with no arguments

B: subclassing Worker, inheritance Person, in the output statement in the default constructor with no arguments

C: define the test class, creating a subclass Worker object

Conclusion :

· When you create a subclass object, priority call the parent class constructor

· The first line of the subclass constructor, the implicit statement super (), the default parent class for calling the no-argument constructor

Requirements: parent class default constructor with no arguments does not exist how to do?

Analysis: When a subclass create the object, you must initialize the object's parent class content, if the parent does not exist in the default constructor with no arguments, you must manually call the other parent structure

// definition of a parent class the Person 
public the Person class { 
    // constructor 
    // constructor with no arguments 
    public the Person (String name) { 

        //System.out.println("Person class constructor with no arguments "); 

        System.out.println ( "configuration parameterized class Person"); 
    } 
}

 

// define a subclass of the Worker 
public the Worker the extends the Person class { 


    // constructor 
    // constructor with no arguments 
    public the Worker () { 

        // Super (); // default constructor with no arguments to call the parent class 
        //System.out.println ( "Worker class constructor with no arguments"); 

        Super ( "John Doe"); 
        System.out.println ( "Worker parameterized class configuration"); 
    } 
}

 

/ * 
    Constructor subclass will have a default surper (); constructor with no arguments used to access the parent class 
    if no parent class constructor with no arguments, parameters can be configured with access to the parent class by surper (parameter) 
 * / 
public class the Test { 
    public static void main (String [] args) { 
        // create a subclass of object class worker 
        worker worker new new worker = (); 

    } 
}

 

operation result:

 

 

The method of rewriting (Override)

·definition:

And the same method as defined parent class subclass phenomenon occurs

·Explanation:

Method overrides the method, also known as replication, cover

Method name, parameter list, return type should be the same

·Precautions:

Superclass private methods can not be overridden

Subclass method access can not be less than the parent class method

Subclass can not throw more exceptions than the superclass method

scenes to be used:

Extend the parent class functions

Parent functionally obsolete, re-implement the functions of the parent class

Four permissions modifier modifies a range, from small to large are:

private, default (nothing to write is the default), protected, public

Access modifiers in 1.Java

This class prvate

This default class, class under this package

This class of protected, under this type package, in different subclasses packages

This class public class under this package, the subclass in different packages, the other class

to sum up

private: emphasis is to their own use

Default: emphasis is to inform the next class of use

protected: emphasis is for use by subclasses

public: emphasis is for everyone to use

2. The process of rewriting and method overloading difference

Overload

Method name: the same

List of parameters: different (or the number corresponding to the location type)

Returns: nothing to do

Define the position: a same class

Rewrite

Method name: the same

Parameter List: same

Return Value: Same

Modifiers: Access is not less than the method being overridden

Defined position: the child parent class

6.java inherited characteristics

· Single inheritance

Java supports only single class inheritance, but the multi-layer support (re) inherit

Java interfaces support multiple inheritance, the syntax is:

A extends Interface Interface B, the interface C, the interface D ....

· Private members can not inherit

Only inherit the parent class of non-private members (member variables, member method)

· Constructor can not be inherited

This construction method is used to initialize the class object

When you create a subclass object, you need to call the parent class constructor to initialize

The parent object is content, if the parent class may be configured to inherit

This operation will cause confusion calls

· The relationship inheritance system "is a" of

Subclass compliance "is a" parent class to use inheritance, otherwise not recommended

Guess you like

Origin www.cnblogs.com/tlidx/p/11453692.html