Crazy Java Learning Notes (----------) inheritance

Source: Internet
Author: User
Tags class definition constant definition modifiers

there is a period of time not updated blog, feel very guilty, these two days busy exam, really no way, can only put a put, fortunately their review of also good, idle nothing, with two blog post, to can make up the emptiness!

Anyway

What is inheritance?

When the same properties and behaviors exist in multiple classes, the content is extracted into a single class, so that multiple classes do not need to define these properties and behaviors, as long as they inherit that class.

Multiple classes can be called subclasses , and this class alone is called a parent class , superclass , or base class .

Subclasses can access non-private properties and behaviors directly in the parent class.

An inheritance relationship between classes and classes is made through the extends keyword.

Class Subdemo extends Demo{}//subdemo is a subclass, the Demo is the parent class
What are the benefits of inheritance?
    • Improve The reusability of your code .
    • Having a relationship between classes and classes is the premise of polymorphism .
Characteristics of inheritance

1.Java only supports single inheritance and does not support multiple inheritance.

A class can have only one parent class, and there can be no more than one parent class. Class Subdemo extends demo{}//okclass Subdemo extends Demo1,demo2...//error

2.Java supports multi-layered (heavy) inheritance (inheritance system).

Class A{}class B extends A{}class C extends b{}
Considerations for using Inheritance
    • If there is a relationship between the classes: is a, you can consider using inheritance.
    • Do not use inheritance in order to inherit some of the functionality.
What is the difference between super and this?

Super is a keyword that represents the storage space identity of the parent class. (Can be understood as a reference to a father)

The use of super and this is similar.

This represents the object's reference (who is called on behalf of whom);
Super represents a reference to the parent class for the current subclass .

Usage Scenarios

    • When a child parent has a member of the same name, it can be distinguished by super;
    • Subclasses you can use the Super statement when you want to call the parent class constructor.

Difference

1. Member variables

this. Variable--    this class of super. Variable-    -    the parent class's

2. Construction method

This (...)    --    This class of super (...)    --    the parent class's

3. Member Methods

This. Method name ()-    -    Super. Method Name ()-    -    the parent class's

Super (); and this (); both are in the first row of the constructor and cannot appear at the same time.

Override of Method (overwrite)

When a method that is identical to the parent class appears in the subclass (except for the permission modifier, the permission modifier is greater than or equal to not including private, the return value type, the method name and the parameter list are the same), an overwrite operation, also known as rewrite or replication, occurs.

The parent class private method, the subclass cannot see, therefore the parent class private method's rewriting also cannot discuss.

Coverage Considerations:

    • When overridden, the subclass method permission must be greater than or equal to the parent class method permission;
    • Static can only be overridden by static.

covered usage Scenarios :

When the subclass needs the function of the parent class, and the function principal subclass has its own content, the methods in the parent class can be copied, so that the function of the parent class is inherited and the subclass-specific content is defined.

What is the difference between method overrides and overloads ?

Method overrides are used when the subclass method is identical to the parent class method, except for the permission modifier, which returns the value type, and the method name and argument list are the same.
Overloading is used in the same class where the method names of the methods are the same, and the argument list is different (not related to the return value type).

use of the constructor method in the child parent class :

    1. During the initialization of a subclass, the initialization of the parent class is performed first. Because the child class is constructed by default, there is a super (). Subclass to use the member variables of the parent class, this initialization must be done before the subclass is initialized. Therefore, the initialization of the parent class is performed first during the initialization of the subclass.
    2. If the parent class does not have an argument-less construction method
    • Use super to invoke the parameter constructs of the parent class. Recommended way.
    • Use this to invoke other constructs of itself.

Static code blocks, construction code blocks, the execution order of the construction methods :

Parent class static code block → subclass static code block → parent class construction code block → parent Class construction method → subclass construct code block → subclass construct method

Final keyword

Final is a keyword that can be used to decorate classes, member variables, and member methods.

features :

    1. The class it modifies cannot be inherited.
    2. The member variable that it modifies is a constant.
    3. It modifies a member method that cannot be overridden by a quilt class.

A final-modified constant definition generally has a writing specification, a final decorated constant name, and all letters capitalized .

The final decorated member variable, which must be initialized, has two types of initialization

    • Display initialization;
    • The constructor method is initialized.
      But it can't be initialized with both.

the difference between final and private :

    1. The final modified class can be accessed;
      Private cannot decorate the outer class, but it can decorate the inner class (in fact, it makes no sense to privatize the outer class).
    2. The final modified method can not be overridden by the quilt class;
      The method of private modification on the surface can be overridden by the quilt class, in fact, it is not possible, the subclass is not see the parent class of private methods.
    3. A final modified variable can be assigned only once when the initialization is displayed or when the constructor is initialized, and will not be allowed to change in the future;
      The private modified variable is not allowed to be accessed or modified directly from the quilt class or other classes in a package, but can be changed and evaluated by the set and get methods.
Polymorphic

Concept :

The different states the objects show at different times.

Prerequisites for polymorphism :

    • You have to inherit or implement a relationship.
    • To have the override of the method.
    • To have a parent class reference, point to the subclass object.

the embodiment of the program :
The reference to the parent class or interface points to or receives its own subclass object .

Benefits and Effects :
The existence of polymorphism improves program extensibility and later maintainability .

Disadvantages :
The parent class calls only the methods in the parent class, and cannot call the subclasses ' unique methods, because you don't know what kind of subclass will inherit you in the future.

characteristics of polymorphic members :

    • member variables : Compile time: see if the referenced variable belongs to a class that has a calling variable;
      Run time: Also see if the class that the reference variable belongs to has a variable called.
      Member variables, whether compiled or run, look at the class to which the reference variable belongs, simply remember the member variable, and compile and run to the left of the equals sign .
    • member Method : Compile time: To see if the referenced variable belongs to a class that has a calling member;
      Run time: To see if the object belongs to a class that has a calling member. If a parent has a method with the same name, the method in the subclass is run, because the method has an overridden attribute.
      compile look to the left to run to see right .
    • static method : Compile time: see if the referenced variable belongs to a class that has a calling variable;
      Run time: Also see if the class that the reference variable belongs to has a variable called.
      both compile and run look to the left of the equals sign .

Must not be able to convert the object of the parent class into a subclass type!

The reference to the parent class points to the subclass object, which can be promoted or cast .

Polymorphism from beginning to finish is the subclass object changing!

Polymorphic down transformation and upward transformation examples, polymorphic transformation solves the disadvantage that a parent reference in a polymorphic state cannot use a subclass-specific member.        Class PolymorphicTest2 {public static void main (string[] args) {Phone P1 = new Nokia ();          Upward transformation, type promotion Nokia No = (Nokia) P1;                      Downward transformation, forcing the reference of the parent class to be converted to subclass type, cannot convert the Nokia type to Moto or Nexus Type No.print ();        The output is phone---null---0 because the method of inheriting the parent class phone p2 = new Moto ();        Moto M = (moto) P2;                    M.print ();        The output is moto---yellow---1599, method override, subclass method overrides parent class method Phone p3 = new Nexus ();        Nexus ne = (nexus) P3;    Ne.print ();    }}class phone{String color;    int price;    public void print () {System.out.println ("Phone---" + color + "---" + price);    }}class Nokia extends phone{String color = "Red";    int price = 1009;    public void print () {//System.out.println ("Nokia---" + color + "---" + price);    }}class Moto extends phone{String color = "yellow";    int price = 1599; public void print () {System.out.println ("Moto---" + COlor + "---" + price);    }}class Nexus extends phone{String color = "BLACK";    int price = 1999;    public void print () {System.out.println ("Nexus---" + color + "---" + price); }}}
Abstraction (abstract)

Abstraction is the abstraction of a common, essential content from multiple things.

Abstract class :

In Java, a method without a method body can be defined, and the concrete implementation of the method is done by the subclass , which is called an abstract method, and the class containing the abstract method is an abstract class.

Origin :

Many objects have the same function, but the specific content of the function is different, then in the extraction process, only the function definition is extracted, not the functional body, then only the function declaration, the method without functional body is called abstract method.

Abstract class features :

    1. Abstract methods must be in the abstract class;
    2. Both abstract methods and abstract classes must be modified by the abstract keyword;
    3. An abstract class cannot create an object with new, because invoking an abstract method makes no sense;
    4. Abstract methods in the abstract class to be used, the child class must be a copy of all its abstract methods, the sub-class object call, if the subclass only covers the part of the abstract method, then the subclass is an abstract class;
    5. Abstract classes can have abstract methods, or can have non-abstract methods, abstract methods for subclass instantiation;
    6. If a class is an abstract class, then inheriting its subclasses is either an abstract class or a rewrite of all abstract methods.
      Special: Abstract methods may not be defined in a class, and this simply does not allow the class to establish an object.

member features of abstract classes :

    • Member variable: can be a variable, or it can be a constant;
    • Construction method: There is a construction method;
    • Member methods: They can be abstract or non-abstract methods.
Abstract class Sunflower Treasure Book {public    abstract void from Palace ();} Class Yeu Bu extends Sunflower Treasure Book {public    void from Palace () {        System.out.println ("scissors");    }} Class 林平 extends Sunflower Treasure Book {public    void from Palace () {        System.out.println ("nail clippers");    } Class Abstracttest  {public    static void Main (string[] args) {        Yue Qun yue = new Yeu Bu ();        Yue. Self-palace ();        Forest of 林平 = new 林平 ();        Lam. Self-palace ();    }}

Abstract class Considerations :

Abstract classes cannot be instantiated, why do they have constructors ?

As long as there is a class definition of the classes inside there must be a constructor. Functions in an abstract class are instantiated for subclasses.

A class does not have an abstract method, why is it defined as an abstract class ?

You don't want to be inherited, and you don't want to be instantiated.

Abstract keyword Abstractions can not coexist with which keywords ?

    • Final: If the method is abstracted, it needs to be overwritten, and final cannot be overwritten, so the conflict.
    • Private: If the function is private, the subclass cannot be accessed directly, how can it be overwritten?
    • Static: The class name can invoke an abstract method without requiring an object. The invocation of an abstract method is meaningless.

Interface (interface)

An interface is a collection of abstract methods and constant values . In essence, an interface is a special kind of abstract class that contains only the definitions of constants and methods, without the implementation of variables and methods.

Format:interface interface Name {}

The appearance of the interface will "multi-inheritance" in another form, that is, "multi-implementation."

Implementation (implements)

Format:class name implements interface name {}

features :

    • The interface cannot be instantiated.
    • If a class implements an interface, it is either an abstract class or a method that implements all the methods in the interface.

member features of the interface :

The member modifiers in the interface are fixed!

    • Member constants: public static final, the variables defined in the interface are global constants, and the modifier can only be these three keywords, can be omitted, the constant name is capitalized.
    • Member methods: Public abstract, the methods defined in the interface are abstract, and two modifier keywords can be omitted.
    • Recommended: Always manually give the modifier.

the difference between inheritance and implementation :

    • A class is called an inheritance relationship between classes: Because the class is abstract or non-abstract, it can define non-abstract methods within it, this method can be used directly in the quilt class, subclass inheritance can be. can only be single-inheritance, multi-tier inheritance. ((Class))
    • Between classes and interfaces is the implementation relationship: Because the methods in the interface are abstract, they must be implemented by subclasses to be instantiated. Can be implemented either single or multiple, and multiple interfaces can be implemented while inheriting a class. (Class) extends (Class) implements (Interface1,interface2 ...)
    • An interface is an inheritance relationship: An interface can inherit from another interface and add new properties and abstract methods, and the interface can inherit more. ((interface) extends (Interface1,interface2 ...)

the difference between an abstract class and an interface :

Member variables

    • Abstract classes can have variables or constants
    • Interfaces can only have constants

Member Methods

    • Abstract classes can have non-abstract methods, or they can have abstract methods.
    • Interfaces can only have abstract methods

Construction method

-Abstract class has a construction method
-Interface has no construction method

The relationship between classes and abstract classes and interfaces

    • The relationship between a class and an abstract class is inherited extends
    • The relationship between a class and an interface is implemented implements

the thought features of the interface :

    The
    1. interface is the external exposure rule;
    2. interface is the function extension of the program ;
    3. interface reduces coupling ; (Modular development, well-defined rules, Everyone realizes their own module, greatly improves the development efficiency)
    4. interface can be used for multiple implementations ;
    5. multiple unrelated classes can implement the same interface;
    6. A class can implement multiple Interfaces that are not directly related to each other;
    7. is similar to an inheritance relationship where there is a polymorphism between an interface and an implementation class.
Athlete and coach case (is thinking analysis)///basketball player and coach table tennis player and coach now basketball players and coaches to go abroad to visit, need to learn English please according to your knowledge, analyze what is the class, which is the abstract class, which is the interface */interface Spea kenglish {public abstract void speak ();} Interface goaboard{public abstract void aboard ();}    Abstract class Person {private String name;    private int age;        Public person () {} public person (String Name,int age) {this.name = name;    This.age = age;    } public void SetName (String name) {this.name = name;    } public String GetName () {return name;    public void Setage (int.) {this.age = age;    } public int Getage () {return age;    }//Eat public abstract void eat ();    Sleeping public void Sleep () {System.out.println ("Zzz ..."); }}//athlete abstract class player extends person {public abstract void study ();} Coach Abstract class coach extends person {public abstract void teach ();}      Basketball player Class Basketballplayer extends Player implements speakenglish,goaboard{public void eat () {  System.out.println (Getage () + "old" + getName () + "eat chicken legs");    } public void Study () {System.out.println (Getage () + "year-old" + getName () + "learning dunk");    } public void Speak () {System.out.println (Getage () + "old" + getName () + "Say Hello World");    } public void aboard () {System.out.println (Getage () + "old" + getName () + "Go aboard"); }}//Ping pong player class Pingpangplayer extends player{public void eat () {System.out.println (Getage () + "year-old" + GetName ()    + "eat eggs");    } public void Study () {System.out.println (Getage () + "age" + getName () + "learning spike"); }}//basketball Coach Class Basketballcoach extends coach implements Speakenglish {public void Eat () {System.out.println (Geta    GE () + "year-old" + getName () + "Chew chicken Claw");    } public void Teach () {System.out.println (Getage () + "year-old" + getName () + "teach Dunk");    } public void Speak () {System.out.println (Getage () + "old" + getName () + "Say Hello Java"); } public void aboard () {SYSTEM.OUT.PRINTLN (Getage () + "old" + getName () + "Go aboard"); }}//Table tennis Coach Class Pingpangcoach extends coach{public void eat () {System.out.println (Getage () + "years old" + getName () +    "Eat egg skin");    } public void Teach () {System.out.println (Getage () + "old" + getName () + "teach Spike"); }}class Playerandcoach {public static void main (string[] args) {//basketball player Basketballplayer bp = new Baske        Tballplayer ();        Bp.setname ("Guo Airen");        Bp.setage (33);        Bp.eat ();        Bp.sleep ();        Bp.study ();        Bp.speak ();        Bp.aboard ();        System.out.println ("***********************");        Basketball coach Basketballcoach BC = new Basketballcoach ();        Bc.setname ("Popovich");        Bc.setage (65);        Bc.eat ();        Bc.sleep ();        Bc.teach ();        Bc.speak ();        Bc.aboard ();        System.out.println ("***********************");        polymorphic person p = new Basketballplayer ();        P.setname ("Kobe Bryant");        P.setage (33);       P.eat (); P.sleep ();        P.study ();        P.speak ();        Basketballplayer bp2 = (basketballplayer) p;        Bp2.study ();        Bp2.speak ();        Bp2.aboard ();    System.out.println ("***********************"); }}
Inner class

One class is defined in another class, and that class inside is called an inner class. The emergence of internal classes has again broken the limitations of Java single inheritance.

Access features :

    • Inner classes can access members of external classes directly, including private members.
    • To access the members of an inner class, an external class must establish an object of the inner class.
      classification and commonality of internal classes :

Common :

    • The inner class is still a separate class, and after compilation, the inner class is compiled into a separate. class file, but preceded by the class name and the $ symbol of the outer class.
    • Internal classes cannot be accessed in an ordinary way. An inner class is a member of an external class, so the inner class is free to access the member variables of the outer class, whether private or not.

member Inner class

There are member variables and member methods in the outer class, and the member inner class takes the whole class as a member of the outer class;
A member inner class is a class that is defined in a class outside of a method;
The object is created in the form of an external class name. Internal class Name Object name = External Class object. Inner class object ;
The member inner class has direct access to the members of the outer class because the inner class holds a reference to an outer class object: The external class name.this;
Members inner classes can have final,abstract,public,private,protected,static modifiers.

Static Inner class

The static inner class is the member inner class plus static modifier statics, defined outside the method in the class.

There are two scenarios for accessing static inner classes in an external class:

    • Non-static members of a static inner class are accessed in an external class:* External class name. Internal class Name Object name = External class name. Internal to image *, need to access by creating objects;
    • Accessing static members of static inner classes in an external class: You can also access them using the format above, or you can use the external class name directly. The internal class name. Member .

Local inner class

A local inner class is a class that is defined in a method.

    • The inner class of a method can only be instantiated within a method that defines the inner class, and it cannot be instantiated outside this method.
    • The inner class object of the method cannot use the non-final local variable of the method in which the inner class resides.

The modifiers that can be used for the inner class of a method are final,abstract;

Method inner classes in a static method can access only external static members .

Anonymous inner class

An anonymous inner class is a simplified notation of an inner class, which is an anonymous object that creates a subclass of an external class or interface with content.
Premise:
An inner class can inherit or implement an external class or interface.
Format:
New external class name or interface name () {override method};
The anonymous inner class can be passed as a parameter, usually when the form parameter of the method is an interface or an abstract class, and the method in the interface is no more than three.

Content decorated with different modifiers (independent of the Inner class)
class member Variable member method construction Method
Private Y Y Y
Default Y Y Y Y
Protected Y Y Y
Public Y Y Y Y
Abstract Y Y
Static Y Y Y
Final Y Y Y

Note that the common rules are as follows:

    • Later, all classes are decorated with public. And, in a Java file, write only one class.
    • Later, all member variables are decorated with private.
    • Later, all member methods are modified with public.
      If it is an abstract class or interface: Public abstract + ...
    • Later, all construction methods are modified with public.
      If the class is a tool class or a singleton class: constructs with private decoration
Four types of permission modifiers different packages ( )
This class is the same package (unrelated class or subclass)subclassdifferent packages (unrelated classes)
Private Y
Default Y Y
Protected Y Y Y
Public Y Y Y Y

Recommended:

    • Member Variable private
    • Construction method Public
    • Member method public

This paper draws on http://www.codeceo.com/article/java-extends.html

Crazy Java Learning Notes (----------) inheritance

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.