inheritance, encapsulation, polymorphic understanding in Java

Source: Internet
Author: User

Java inheritance, encapsulation, polymorphism in

The understanding of Inheritance:

1. Inheritance is one of the three characteristics of object-oriented, and also an important means to realize code reuse. Java inheritance has the characteristics of single inheritance, with only one direct parent class per subclass.

2, Java inheritance through the extends keyword to implement, the implementation of the inherited class is called a subclass, the inherited class is called the parent class (some also known as the base class, the superclass), the parent class and the child class relationship, is a general and special relationship. Like fruit and apples, apples inherit fruit, apples are children of fruit, fruit is Apple's parent, Apple is a special kind of fruit.

3, Java uses extends as the Inheritance keyword, the extends keyword in English is the extension meaning, but is not the inheritance. Why the domestic translation of extends into succession? In addition to the historical reasons, it is also reasonable to translate extends into inheritance: The subclass extends the parent class, it will be able to get all the properties and methods of the parent class, which is very similar to the inheritance in Chinese (The offspring inherit a fortune from their fathers). It is worth noting that: Java subclass cannot get the constructor of the parent class.

4. Example:

class baseclass{

Public double weight;

Public void info () {

System. out. println ("My Weight is" +weight+ "kg");

}

}

Public class ExtendsDemo001 extends baseclass {

Public Static void Main (string[] args) {

Create a ExtendsDemo001 object

ExtendsDemo001 ed = new ExtendsDemo001 ();

The ExtendsDemo001 itself does not have a weight property, but the parent class of ExtendsDemo001 has a weight attribute and can also access the properties of the ExtendsDemo001 object

Ed.weight = 56;

Call the info () method of the ExtendsDemo001 object

Ed.info ();

}

}

The result is: my weight is 56.0 kilograms.

5. Java classes can have only one parent class. This sentence is wrong, it should be said: Java class can only have a direct parent class, can have an infinite number of indirect parent classes, such as:

Class Fruit extends plant{...}

Class Apple extends Fruit {...}

To override the parent class's method:

1, most of the time, the subclass is always based on the parent class, adding new properties and methods. However, there is one exception: subclasses need to override methods of the parent class. Birds, for example, contain a way to fly, in which ostriches are a special kind of bird, so ostriches are also a subclass of birds, so it will be a way to fly from birds, but this way of flying is obviously not suitable for ostriches, and for this reason, ostriches need to rewrite the methods of birds.

2. The following code can help to understand rewriting:

1) class bird{

2) The Fly () method of the//bird class

3) private void Fly () {

4) System. out. println ("I want to fly in the sky");

5)}

6)}

7) public class ocerridetest extends bird{

8)//Override the Fly () method of the bird class

9) public void Fly () {

System. out. println ("I can only run on the ground");

11)}

Public static void main (string[] args) {

13)//Create Ocerridetest Object

Ocerridetest ot = new ocerridetest ();

() ot.fly ();

16)}

17)}

Print Result: I can only run on the ground

This seed class contains a method of the parent class with the same name as a method override, also known as a method override (override).

The override of the method follows the "two and two small and one big" rules:

⑴ "Two identical": Method name is the same; formal parameter list is same.

⑵ "Two small": The return type of a subclass method should be smaller or equal than the return value type of the parent class method, and the exception class that the subclass method declaration throws should be smaller or equal than the exception class that the parent method declaration throws.

The ⑶ subclass method should have greater or equal access than the parent class method

In particular, it is important to note that both the Overwrite method and the overridden method are either class methods or instance methods, not a class method, or an instance method, for example, the following code will have a compile error:

Class baseclass{

public static void Test () {...}

}

Class Subclass extends Baseclass{

public void Test () {.......}

}

To invoke the Fly () method in the parent class, simply add the following code to the Fly () method in the subclass:

Super.fly ();

Note: Super and this do not appear in the static method

Calling the parent class constructor

1, see the following program-defined Basehe Sub class, where the sub class is a subclass of the base class, the program uses super in the Sub class constructor to invoke the initialization code in the base constructor.

class base{

Public double size;

Public String name;

Public Base (double size, String name) {

this. size=size;

this. name=name;

}

}

Public class Sub extends base{

Public String color;

Public Sub (double size, string name, string color) {

Call the parent class constructor in the subclass constructor and use the super call to implement the

Super (Size,name);

this. Color = color;

}

Public Static void Main (string[] args) {

Sub s = New sub (5.6, "Test Object", "Red");

System. out. println (s.size+ "------" +s.name+ "------" +s.color);

}

}

The print result is: 5.6------test Object------Red

Static initialization blocks

1. If the static modifier is used when defining the initialization block, the initialization block becomes a static initialization block, also known as a class initialization block. Static initialization blocks are class-dependent, and the system executes static initialization blocks during the class initialization phase, rather than when the object is created. So static initialization blocks are always executed first than normal initialization blocks

Understanding of Encapsulation:

1, Encapsulation (encapsulation) is one of the three characteristics of object-oriented, it refers to the object's state information is hidden inside the object, does not allow external programs to access the object's internal information directly, but through the method provided by the class to achieve internal information operation and access.

2, master the use of access control, the following by using reasonable access control to define a person class, this person class has achieved a good encapsulation. The code is as follows:

Public class person {

Public Static void Main (string[] args) {

Person p = new person ();

P.setage (10);

System. out. println (P.getage ());

}

Use the private adornment to hide these properties.

Private String name;

Private int age;

Provides methods to manipulate the Name property

Public void setName (String name) {

Perform a reasonable check on the name

if (Name.length () > 6 | | name.length () < 2) {

System. out. println ("Your name does not meet the requirements");

}Else{

this. Name = name;

}

}

Public String GetName () {

return this. Name;

}

Provides methods to manipulate the Age property

Public void setage (int age) {

if (age>100 | | age<0) {

System. out. println ("Your age must be between 0~100");

}Else{

this. Age = age;

}

}

Public int getage () {

return this. age;

}

}

Operation Result: 10

A polymorphic understanding:

1, polymorphism (polymorphism) is one of the three main characteristics of object-oriented.

2. Java reference variables have two types: one is a compile-time type and one is a run-time type. The type at compile time is determined by the type used when declaring the variable, and the run-time type is determined by the object that is actually assigned to the variable. If the compile-time type and run-time type are inconsistent, the so-called polymorphism (polymorphism) occurs

First look at the following program:

class superclass{

Public int book = 6;

Public void Base () {

System. out. println ("normal method base () of the parent class");

}

Public void Test () {

System. out. println ("Method for north-covered in the parent class");

}

}

Public class PloymorphismTest001 extends superclass{

Redefine a book instance property, overriding the book instance property of the parent class

Public String book = "Java Madness handout";

Public void Test () {

System. out. println ("Methods for overriding the parent class in subclasses");

}

Private void Dmeo () {

System. out. println ("Common method in subclasses");

}

Main method

Public Static void Main (string[] args) {

The following compile-time type is exactly the same as the run-time type, so there is no polymorphic

Superclass sc = new superclass ();

System. out. println ("book1=" +sc.book);//Print Result: 6

The following two calls will execute the superclass method

Sc.base ();

Sc.test ();

The following compile-time type is exactly the same as the run-time type, so there is no polymorphic

PloymorphismTest001 pt = new PloymorphismTest001 ();

System. out. println ("book2=" +pt.book);//print Result: Java Madness handout

The following call executes the base method that inherits from the parent class

Pt.base ();

The following call executes the test method of the current class

Pt.test ();

The following compile-time type is not the same as the run-time type, polymorphism occurs

Superclass SSCC = new PloymorphismTest001 ();

The result is that the parent class property is accessed

System. out. println ("book3=" +sscc.book);//Print Result: 6

The following call will perform the inheritance from the parent class to the base method

Sscc.base ();

The following call executes the test method of the current class

Sscc.test ();

Because the SSCC compiler type is the Superclass,superclass class does not provide the demo () method

So the following code compiles with an error

Sscc. Demo ();

}

}

The result of the program operation is:

Book1= 6

Normal method base for parent class ()

Methods for North overrides in parent class

book2= Java Madness Handout

Normal method base for parent class ()

Methods that override the parent class in a child class

Book3= 6

Normal method base for parent class ()

Methods that override the parent class in a child class

The main method of the above program shows the creation of 3 reference variables, for the first two reference variables SC and PT, they compile-time type and run-time type exactly the same, so call their properties and methods are very normal, no problem at all. But the third reference variable, SSCC, is special, it compiles with a type of superclass, and the run-time type is PloymorphismTest001 when the test method of the reference variable is called. is actually executing the PloymorphismTest001 test method in the class, which is polymorphic.

When a subclass object is assigned directly to the parent class reference variable, such as superclass SSCC = new PloymorphismTest001 () above, the compile-time type of this SSCC reference variable is superclass, While the run-time type is PloymorphismTest001, when the runtime invokes the method of the reference variable, its method behaves like the behavior of the subclass method, rather than the behavior of the parent method, which will occur with the same type of variable, and when the same method is executed, different behavior characteristics are present, which is polymorphic.

Special Reminders:

Unlike the method, the object's properties are not polymorphic, such as the SSCC reference variable above, when the program outputs its book property, not the instance properties defined in the output PloymorphismTest001 class, but the instance properties of the superclass class.

Attention:

We define a variable p by using the object P = new person () code, this p can only call methods of the object class, not the method defined in the person class.

inheritance, encapsulation, polymorphic understanding in Java

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.