Java inheritance, abstract classes, and interfaces; java inherits abstract Interfaces

Source: Internet
Author: User

Java inheritance, abstract classes, and interfaces; java inherits abstract Interfaces

1. Inheritance (Extends)

What is inheritance?

Inheritance is a simulation of the concept of "classification" in real life.

Lions have all the basic characteristics of animals, but they also have their own unique characteristics. This is an important feature of "inheritance" relationships: generally referred to as "IS_A" relationships, the UML class diagram can be expressed as follows:

Inherited syntax

Class subclass name extends parent class name {

......

}

Note:

Parent class and super class (super class): usually refers to the direct upper level;

Base class: generally refers to "upper-level superiors", including direct superiors ";

For example:

The subclass automatically owns the parent class declarationPublicAndProtectedThis is one of the embodiment of the inheritance feature.

Access Permissions of classes under inheritance Conditions:

Public:Free access

Private:Inaccessible

Protected:Sub-classes in the same package can be accessed, and sub-classes in the other package (derived from the same parent class) can also be accessed

Default:If no permission is specified, classes in the same package can be accessed by default.

Call the constructor under the Inheritance Condition

First, what are the findings of this code?

 1 class Grandparent { 2  3     public Grandparent() { 4         System.out.println("GrandParent Created."); 5     } 6  7     public Grandparent(String string) { 8         System.out.println("GrandParent Created.String:" + string); 9     }10 }11 12 class Parent extends Grandparent {13 14     public Parent() {15         //super("Hello.Grandparent.");16         System.out.println("Parent Created");17        // super("Hello.Grandparent.");18     }19 }20 21 class Child extends Parent {22 23     public Child() {24         System.out.println("Child Created");25     }26 }27 28 public class TestInherits {29 30     public static void main(String args[]) {31         Child c = new Child();32     }33 }
TestInherits. java

Observe the output and draw the following conclusions:

1 ). when the parent class is inherited, the non-argument constructor of the parent class is called by default. If there is no constructor in the parent class, an error is reported for the non-argument constructor of the Child class, if you want to call a constructor with parameters, you need to use super. It shows that the constructor with parameters of GrandParent is called, and super () must be placed in the first row of the subclass constructor.

2). The initialization parent class is displayed before the initialization subclass. If a father has a son only when it comes out, it is impossible for him to come out without a father son.

3). Call the attributes of the parent class in the subclass. The form of super. And this is different from that of the parent class and subclass.

Class that cannot be inherited

FinalClass name {

}

1) UseFinalThe declared method cannot be overwritten.

2)FinalDeclared variables cannot be changed.

3) ExploitationFinal, You can design a special"Read-Only""Immutable class".

 

"Immutable class "?

After you create an "immutable class" object, the attributes of this object cannot be modified, and a new subclass cannot be derived from this class. String is a typical example.

Usage: It can be conveniently and securely used in multi-threaded environments;

They can be accessed without locking, thus providing high performance.

Instance: Address. java

1 public final class Address 2 {3 private final String detail; 4 private final String postCode; 5 6 // initialize two instance attributes in the constructor 7 public Address () 8 {9 this. detail = ""; 10 this. postCode = ""; 11 12} 13 public Address (String detail, String postCode) 14 {15 this. detail = detail; 16 this. postCode = postCode; 17} 18 // only provides the getter method 19 public String getDetail () 20 {21 return this. detail; 22} 23 24 public String GetPostCode () 25 {26 return this. postCode; 27} 28 // rewrite the equals method to determine whether the two objects are equal. 29 public boolean equals (Object obj) 30 {31 if (obj instanceof Address) 32 {33 Address ad = (Address) obj; 34 if (this. getDetail (). equals (ad. getDetail () & this. getPostCode (). equals (ad. getPostCode () 35 {36 return true; 37} 38} 39 return false; 40} 41 public int hashCode () 42 {43 return detail. hashCode () + postCode. hashCode (); 44} 45}
Address. java

 

Relationship between subclass and parent class Method

There are three possible cases between subclass and methods defined by fresh:

Extends ):The parent class of the method defined by the subclass does not have the same name.

Override ):The subclass parent class defines the same method ------ note the "Overwrite principle" to be followed when overwriting, for example, static methods cannot be overwritten.

Overloads ):Subclass has a method with the same name as the parent class, but the parameter types or numbers of the two are different.

Top-level base class Object

In Java, all classes are derived from objects. This class defines the following method:

Magic "+"

Read this Code:

 

 

 

 

 

Note that in the last sentence, a substring is added to an object and the result is as follows:

 

 

 

 

Why?

The Fruit class overwrites the toString method in the Object class.

Conclusion:

In"+"When an object is connected to a String object, the toString () method is called implicitly. By default, this method returns"Class Name @ + hashCode". To return meaningful information, subclass can override the toString () method.

Java "method override" syntax rules

  • Static methods cannot be overwritten.
  •  

    Ii. abstraction (AbstractAnd interfaces (Interface)

    Abstract classes and abstract methods

  • An abstract class can contain non-Abstract methods and member variables. Classes that contain abstract methods must be abstract classes, but methods in abstract classes are not necessarily abstract methods.
  • Three "types" of abstract classes"

    Note:

  • The following mode is always true:
  • Why do I enter the "interface" in object-oriented programming "?

    In C ++, inheritance is multi-inheritance, but in Java, it can only be a single inheritance. To make up for this, the concept of interfaces is introduced.

    If you want to inherit other classes, you can define other classes as interfaces (in fact, they are also special classes) and keywordsInterfaceUsedDefinitionInterface, keywordImplementsUsed for interfaceInheritance, The interface can inherit multiple, so you can use the interface to implement multiple inheritance.

    Syntax features of "interfaces" in Java

    Interface Usage

    Variable of interface type = new of interface type ();

    Interface Expansion

    You can use an inherited interface to expand an existing interface and form a new interface.

    Example:

    Classes that implement sub-interfaces must implement all methods defined by the "parent" and "sub-" interface to be instantiated (I .e., a new object ).

    Define constants Using Interfaces

    Differences between interfaces and abstract classes

    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.