Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the concept of Java inheritance and Polymorphism and how to implement it

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "what is the concept of Java inheritance and polymorphism and how to achieve it". The editor shows you the operation process through an actual case. The operation method is simple and fast, and it is practical. I hope this article "what is the concept of Java inheritance and polymorphism and how to achieve it" can help you solve the problem.

1. The concept of inheritance

Inheritance mechanism: object-oriented programming is the most important means by which code can be reused, allowing programmers to expand on the basis of maintaining the original class characteristics, add new functions, and generate new classes to become derived classes / subclasses. The main problem solved by inheritance is the extraction of commonness and the reuse of code.

2. The grammar of inheritance

To represent the inheritance relationship between a class and a class, you need the keyword extends. The syntax is as follows:

Modifier class subclass / derived class extends parent class / base class / superclass {

/ /.

}

The subclass inherits the member variables or member methods of the parent class to the subclass

After the subclass inherits the parent class, it must add its own unique members, which is different from the base class.

3. The member of the parent class accesses (1) access to the member variable of the parent class in the subclass

When there is no member variable with the same name, normal access is fine.

There is a member variable with the same name, using (super. (variable name) to implement the access of parent class member variables

Public class Base {int a; int b; int c;} public class Derived extends Base {int a; / / has the same name as member an in the parent class and has the same type char b; / / has the same name as member b in the parent class, but the type is different public void method () {a = 100; / / access the an inherited by the parent class, or the an added by the subclass itself? B = 101; / / access the b inherited by the parent class, or the b added by the subclass itself? C = 102; / / the subclass does not have c, and the access must be the c}} inherited from the parent class.

When accessing member variables, you have priority access to your own member variables. That is, when a member variable with the same name is accessed, the access to the subclass is given priority. That is, the subclass hides the members of the parent class

Member variable access follows the principle of proximity, they have priority to their own, if they do not, then look for it in the parent class.

(2) the member method of accessing the parent class in the subclass

The name of the member method is different, so you can access it normally.

The name of the member method is the same, and you can use [super. Method name] access the parent class method with the same name

If the parameter list of the method with the same name of the parent class and the subclass is different (overloaded), the appropriate method access is selected based on the parameters passed when the method is called.

If the parent class and subclass have the same method prototype of the same name, access the subclass's

4. Super keyword

The main purpose of the super keyword is to access members of the parent class with the same name in the subclass method. (can only be used in non-static methods)

Public class Base {int a; int b; public void methodA () {System.out.println ("methodA () in Base");} public void methodB () {System.out.println ("methodB () in Base");} public class Derived extends Base {int a; char b / / constitute overloaded public void methodA (int a) {System.out.println ("method () method in Derived") with methodA () in parent class;} / / rewrite public void methodB () {System.out.println ("methodB () method in Derived") with methodB () in parent class;} public void methodC () {a = 100; / / equivalent to: this.a = 100 B = 101; / / equivalent to: this.b = 101; / / access the member variable of the parent class with the help of the super keyword / / super is to get the part of the subclass object inherited from the base class super.a = 200; super.b = 201; methodA (); / / No parameters are passed, access the methodA () methodA (20) in the parent class / / pass the int parameter, access the methodA (int) methodB () in the subclass; / / access directly, you will always access the methodA () in the subclass, and the base class cannot access super.methodB (); / / access the methodB ()} 5 of the base class, subclass constructor

When constructing a subclass object, you need to first call the constructor of the parent class, and then execute the constructor of the subclass.

Public class Base {public Base () {System.out.println ("Base ()");} public class Derived extends Base {public Derived () {/ / super () / / Note that the no-parameter constructor of the base class is called by default in the subclass constructor: super (), / / when the user does not write, the compiler automatically adds it, and super () must be the first statement in the subclass constructor, / / and System.out.println ("Derived ()") can only appear once;}}

If the parent class shows a defined no-parameter or default constructor, there is an implicit super () call by default on the first line of the constructor of the subclass.

When a parent class defines a constructor with parameters, the compiler no longer generates a default constructor for the subclass, but requires an explicit definition of the subclass and calls the appropriate parent constructor in the subclass constructor.

In the subclass construction method, super (...) Call the parent class constructor, which must be the first statement of the subclass constructor

Super (…) Can only occur once in a subclass constructor, and cannot appear at the same time as this

6. Super and this

Both super and this can be used in member methods to access member variables and call other member functions, and both can be used as the first statement of the constructor, so what's the difference between them?

(1) similarities

Are all keywords of java.

Can only be used in non-static methods of a class to access non-static member methods and properties

Must be the first statement in the constructor and cannot exist at the same time

(2) differences

This is a reference to the current object, and super is a reference to a member of a subclass object inherited from the parent class

This is a hidden parameter of a non-static member method, while super is not a hidden parameter

In the constructor: this () is used to call the constructor of this class, and super () is used to call the constructor of the parent class. Both calls cannot appear in the constructor at the same time.

There must be a call to super () in the constructor of the subclass, but not if the this () user does not write

7. Code block execution order

[general class]

The static code block is executed first, and only once, during the class loading phase

When an object is created, the instance code block is executed, and finally the constructor is executed

[execution order on inheritance relationship]

The parent class static code block takes precedence over the subclass static code block execution, the earliest execution

The parent class instance code block and the parent class constructor are then executed

The instance code block and constructor of the subclass are finally executed

When the subclass object is instantiated for the second time, the static code blocks of the parent class and subclass are no longer executed

8. Inheritance mode

[note] multiple inheritance is not supported in Java

Super can only refer to a direct parent class

Inheritance relationship is generally no more than three layers.

9. Final keyword

When you modify a variable, it represents a constant (cannot be modified)

Decorating class: this class cannot be inherited

Modification method: indicates that the method cannot be overridden

10. Inheritance and combination

Both combination and inheritance can achieve code reuse. Composition does not involve special syntax (such as the extend keyword), but simply takes an instance of one class as a property of another class.

Inheritance indicates that the relationship between objects and objects is is-a

Combination indicates that the relationship between objects and objects is has-a

General advice: use combinations as much as possible

2. Polymorphism 1. Upward transformation

The upward transformation is safe by invoking the subclass object through a reference to the parent class type

[timing of upward transformation]

Direct assignment

Methods to transfer parameters

The return value of the function

Public class TestAnimal {/ / 2. Function parameter: the formal parameter is a parent class reference, and you can receive the object public static void eatFood (Animal a) {a.eat ();} / / 3 of any subclass. Return value: return any subclass object public static Animal buyAnimal (String var) {if ("dog" = = var) {return new Dog ("dog", 1);} else if ("cat" = = var) {return new Cat ("cat", 1);} else {return null }} public static void main (String [] args) {Animal cat = new Cat (Yuanbao, 2); / / 1. Direct assignment: the subclass object is assigned to the parent object Dog dog = new Dog ("Xiao Qi", 1);}}

Advantages and disadvantages:

Pros: make the code more flexible

Cons: unable to access methods specific to subclasses

2. Rewrite

Same function name, same argument list, same return value, or [covariant type] (parent-child class relationship)

[rules for method rewriting]

Access to an overridden method cannot be lower than that of the original method in the parent class

Methods and constructors modified by static, private and final in the parent class cannot be overridden

To rewrite the method, you can use the @ override annotation to display the specification (to help us do some validation). For example, if the method name is misspelled, the compilation will report an error.

Overridden return values can be of different types, but must have a parent-child relationship.

A method modified by final is called a sealing method, which cannot be overridden.

External classes can only be public or default permissions

[dynamic binding and static binding]

Dynamic binding: the condition under which it occurs (1, the parent class reference references the subclass object; 2, through the parent class reference, you can access the methods in the subclass). Late binding, that is, the behavior of a method cannot be determined at compile time, and you need to wait until the program is running before you can determine which class's method is called.

Static binding: pre-binding, at compile time, the specific calling method is determined according to the type of parameters passed by the user (function overloading)

3. Polymorphism

The idea that a reference calls the same method can take different forms, which is called polymorphism. Do not call overridden methods in the constructor of the parent class.

[conditions for polymorphic realization]

Must be under the condition of inheritance

The subclass overrides the parent method

Call the overridden method through the parent class reference

An upward transformation has taken place.

Public class Animal () {String name; int age; public Animal (String name, int age) {this.name = name; this.age = age;} public void eat () {System.out.println (name + "eat");}} public class Cat extends Animal {public Cat (String name, int age) {super (name, age) } @ Override public void eat () {System.out.println (name+ "eat fish ~");}} public class Dog extends Animal {public Dog (String name, int age) {super (name, age);} @ Override public void eat () {System.out.println (name+ "eat bones ~") }} public class TestAnimal {/ / when compiling the code, the compiler does not know which method to call until the specific object referenced by formal parameter an is determined. When compiling the code, the compiler does not know which method to call until the Dog or the method / / of eat in Cat runs. / / Note: the parameter type here must be the parent class type to public static void eat (Animal a) {a.eat (). } public static void main (String [] args) {Animal animal1 = new Cat ("Yuanbao", 2); Animal animal2 = new Dog ("Xiao Qi", 1); eat (animal1); eat (animal2);}}

[note] all classes in Java inherit the Object class by default

This is the end of the introduction to "what is the concept of Java inheritance and Polymorphism and how to implement it". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report