Java Learning notes-4. Inheritance and polymorphism

Source: Internet
Author: User
Tags float double

I. The mechanism of succession

1. Inheritance: Allow a class to be an extended version of another class

2. Single inheritance: A class inherits only one parent class multiple inheritance: One class inherits multiple parent classes

Java only supports single inheritance, C + + supports multiple inheritance

Ii. Inheritance of Classes

1. Form:

Class Subclass extends BaseClass {

Subclass class body, defining a new member of a subclass

}

All classes in Java inherit the class Java.lang.Object, directly or indirectly.

2. Construction method

(1) Explicit construction method form: Super (parameter table);

When the system executes to this statement, it determines which construction method in the parent class is called based on the parameter table (the parameter table can be empty)

Note: When you use Super to call the parent class construction method, you must put the first sentence in the subclass construction method

The super parameter cannot be an object member of this or the current object, because the construction method is not yet complete

(2) Implicit construction method: If the subclass does not have an explicit constructor method, the default constructor method of the parent class and the default constructor of the subclass are called in turn

3. Initialization of sub-class objects

Order: (1) class file Loaded into Class (2) from parent class to subclass, initialize static member variable sequentially

(3) Call the class construction method (first called the parent class) from the parent class to the subclass, and initialize the member variable (4) of the object in sequence

(5) initialize the block and construction method from the object class, then return to the initialization block and construction method that executes its subclasses, and so on, until the initialization block and constructor method of the current class

4. The object of the subclass has all the members defined in the parent class, but cannot access private members in the parent class (private)

5. Overwrite: Define a method in the subclass that is exactly the same as the method name and parameter table in the parent class

Note: If the method func () in the subclass override the method in the parent class, the access control of the method func () in the subclass cannot be reduced relative to the parent class's Func () method.

The exception that is thrown by the Func () method declaration in a subclass cannot exceed the declaration of the Func () method in the parent class.

Example: In a parent class:

Double Getincome () {

return wage + bonus; Wage and bonus are both private-modified

}

Sub-class:

Double Getincome () {

return Super.getincome () + dividend; Super represents calling the Getincome method of the parent class

}

Iii. Object type conversion and polymorphism

1. Polymorphism: The same entity has multiple forms at the same time, which can improve the reusability of code

2. Object type conversions are divided into upward transformation and downward transformation

Upward transformation: Objects of subclasses are treated as objects of the parent class to use

This type conversion is safe, but it loses the newly defined information in subclasses

Down transformation: Objects of the parent class are used as objects of subclasses (casting required)

This type of conversion is unsafe and may cause information to be missing.

The overwrite mechanism in 3.Java allows you to define method names, parameter tables, and methods with the same return values but different method bodies in several classes of the inheritance relationship, which, when the program is run, determines which method to execute based on the type of object being referenced, which is called dynamic binding (that is, the runtime determines which method to execute)

In Java, only private methods, final decorated methods, static methods are static bindings (that is, compile-time bindings).

Iv. Keyword Final

1.final can be used to modify variables, methods, and classes, which means that the modified object can only be initialized once and cannot be changed.

When the final decoration method is parametric, the value of the parameter variable is not modified in the representation method

The static member variable of the final decoration must be initialized at the time of declaration or in a static initialization block

Final-modified methods cannot be overwritten during inheritance

A final decorated class cannot be inherited by another class

The 2.final class has no subclasses, the member methods of the final class are not overwritten, and the member variables of the final class are not necessarily constant variables

Abstract methods and abstract classes

1. Abstract method: Only method name, parameter table, return value, no method body (cannot be executed)

Declaration Syntax: abstract returntype function (Parameters list); No curly braces

Use the keyword abstract to decorate before a method declaration

Abstract methods can be overridden to write

Static methods, private methods, and final-decorated methods cannot be overwritten, and therefore cannot be defined as abstract methods

2. Abstract class: Class with no specific object, syntax: Abstract with keyword before class definition

3. Note:

(1) If a class contains an abstract method, the class must be defined as an abstract class, but an abstract class can have no abstract method

(2) Abstract class is not available to create objects

4. If a subclass of an abstract class does not implement an abstract method of the parent class, this subclass is also an abstract class and must be decorated with the keyword abstract

Effect: An abstract class guarantees that all its subclasses, if instantiated, must implement an abstract method declared in an abstract class

Vi.. Interface

1. Definition form: interface InterfaceName {...}

The member method defaults to abstract, public, and the member property defaults to static, final decorated

The interface simply provides a form, and the specific implementation details are given to its class to complete

Because the interface does not involve a specific implementation, the member variable in the interface is a static constant variable, which defaults to static and final decoration

2. Class implements an interface: Class MyClass implements A, B, C {...}

A class can implement multiple interfaces

Note: Although there is no explicit declaration method in the interface is public, but the default access control in the interface is public, and the default access control in the class is in-package friendly, the method must be decorated in class with the

3. Selection of interfaces and abstract classes:

Multiple inheritance is not supported between classes in Java, but classes can implement multiple interfaces

If the class needs to include implementations of some methods, it must be implemented as an abstract class, and in other cases, the use of interfaces is preferred, making the program easier to extend

Vii. internal classes and anonymous inner classes

1.Java allows you to define another class within the class, which is called the inner class of the class, and the class containing the inner class is the outer class

Methods, properties in inner classes that can access external classes

Unlike a generic class: An external class can access private members of its inner class

2. Only internal classes with public or default access control can be accessed in other classes, and private inner class objects cannot be created

And you must have an external class object when creating an inner class object, but you can create an object of a static inner class by using the Outer class class name

3. Creating an inner class object in another class

Cases:

classOuterclass {classinnerclassa{}//external class objects are required when creating an inner class object    Private classinnerclassb{}//Cannot create private inner class object    Static classinnerstaticclass{}//static inner class objects can be created by class name}classInnerclassdemo { Public Static voidMain (string[] args) {Outerclass out=NewOuterclass (); Outerclass.innerclassa Inner= out.NewInnerclassa (); Outerclass.innerstaticclass a=NewOuterclass.innerstaticclass (); }}

4. Anonymous inner class: Inner class with no class name

Anonymous inner class cannot define a constructor method

Viii. Object class

1. Class Java.lang.Object is the parent class for all Java classes

The purpose of designing the object class: (1) You can declare an object reference of type object to any type of object

(2) Some methods defined in the object class that are automatically inherited to all classes

Common methods for 2.Object classes:

(1) Boolean equals (object oth) Effect: Compares two object references for equality

(2) string toString () Action: Convert an object to a string

(3) Finalize () function: Release object

(4) Wait () function: Thread wait

(5) Notify () function: wake-up thread

Note: Method (1) must be covered when used

Method (2) The returned string is composed of the type that the object refers to, the character @, the unsigned hexadecimal number of the object hash code, which is generally of little value and must be covered

Nine, Packaging class

1.8 Basic data types: byte short int long float double char Boolean

Corresponding wrapper class: Byte short Integer Long Float Double Character Boolean Void

2. Conversion of data of basic data type to wrapper class object: Typevalue () method

Cases:

int a = tennew  Integer (a); System.out.println (Obj.intvalue ());

3. Wrapping the conversion of data and strings of a class object or base data type: ToString Method

Form: Public String toString ();

To convert a string to an object of a wrapper class:

Example: Public Integer (String s);

Convert a string to data of the base data type: valueof (String) method or Parsetype () static method

4. After the JDK5.0 version, the Java Virtual Machine supports the automatic boxing, unpacking mechanism

Auto-Boxing: Automatically encapsulates data of a basic data type as the appropriate wrapper class object

Auto-unpacking: Automatically extracts data from a basic data type from a wrapper class object

Java Learning notes-4. Inheritance and polymorphism

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.