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

How to implement inheritance in Java

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

Share

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

This article focuses on "how to achieve inheritance in Java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to realize inheritance in Java"!

one。 Inherit

As we all know, our Java language is an object-oriented programming language. Whenever we mention the features of Java, we must think of inheritance, polymorphism and encapsulation in Java.

1.1 implementation of inheritance

The concept of inheritance

Inheritance is one of the three major object-oriented features, which can make a subclass have the properties and methods of the parent class, redefine it in the subclass, and append properties and methods.

Implement the format of inheritance: inheritance is implemented through extends

Format: class subclass extends parent class {}

For example: class Dog extends Animal {}

The benefits of inheritance

Inheritance allows a relationship between a class and a class, a child-parent relationship, and after a child-parent class is generated, the subclass can use non-private members of the parent class.

In order to give you a better understanding of the format, we now give a simple case to illustrate:

Public class Fu {public void show () {System.out.println ("show method called");}} public class Zi extends Fu {public void method () {System.out.println ("method method called");}} public class Demo {public static void main (String [] args) {/ / create an object and call the method Fu f = new Fu (); f.show (); Zi z = new Zi (); z.method (); z.show ();}}

The results of this case are as follows:

1.2 advantages and disadvantages of inheritance

Inherit benefits

Improves the reusability of code (members of multiple classes that are the same can be placed in the same class)

Improves the maintainability of the code (if the code of the method needs to be modified, you can modify it in one place)

Inherit malpractice

Inheritance creates a relationship between classes, and the coupling of classes is enhanced. When the parent class changes, the subclass implementation has to change, weakening the independence of the subclass.

Inherited application scenarios:

To use inheritance, we need to consider whether there is an is..a relationship between classes, and we should not use inheritance blindly.

The relationship of is..a: who is one of whom, for example, teachers and students are a kind of people, that person is the parent class, and students and teachers are the subclass.

two。 Member access characteristics in inheritance 2.1 access characteristics of variables in inheritance

Access a variable in a subclass method, using the principle of proximity.

Subclass local range search

Subclass member scope search

Parent class member scope search

If not, report the mistake (regardless of the father's father.)

Let's use the above case to illustrate:

Class Fu {int num = 10;} class Zi {int num = 20 String public void show () {int num = 30 X system. Out.println (num);}} public class Demo1 {public static void main (String [] println) {Zi z = new Zi (); z.show (); / / output the local variable 30} in the show method

The specific results of this case are as follows:

2.2 super

ThisVS.super keyword:

This: a reference that represents an object of this class

Super: the identity that represents the storage space of the parent class (which can be understood as a reference to the parent object)

Use of this and super:

Member variables:

This. Member variables-access member variables of this class

Super. Member variables-access parent class member variables

Member method:

This. Member methods-access the member methods of this class

Super. Member method-access parent class member method

Construction method:

This (…) -access the constructor of this class

Super (…) -access the parent class constructor

2.3 access characteristics of constructors in inheritance

Note: all constructors in the subclass access the no-parameter constructor in the parent class by default

The subclass inherits the data from the parent class and may also use the data from the parent class. Therefore, before subclass initialization, be sure to initialize the parent class data, because the first statement of each subclass constructor defaults to: super ()

Question: what if there is no parameter constructor in the parent class, only the parameter constructor?

Call the parameterized constructor of the parent class by using the super keyword to display

Provide a no-parameter construction method in the parent class

Recommended options:

The method of non-parameter construction is given by myself.

2.4 access characteristics of member methods in inheritance

Access a method through a subclass object

Subclass member scope search

Parent class member scope search

If not, report the mistake (regardless of the father's father.)

2.5 super memory diagram

Objects are in heap memory and there is a separate super area to store the data of the parent class.

2.6 method rewriting

1. Method rewriting concept

The subclass has exactly the same method declaration as in the parent class (the method name must be the same, the parameter list must be the same)

2. Application scenarios of method rewriting

When the subclass needs the function of the parent class, and the functional subject subclass has its own unique content, you can override the methods in the parent class, so that it not only follows the function of the parent class, but also defines the unique content of the subclass.

3. Override comments

It is used to check whether the current method is rewritten and plays the role of [verification].

2.7 considerations for method rewriting

Considerations for method rewriting

Private methods cannot be overridden (parent private member subclasses cannot be inherited)

Access to subclass methods cannot be lower (public > default > private)

We still use the previous case to illustrate this problem:

Public class Fu {private void show () {System.out.println ("show () method called in Fu");} void method () {System.out.println ("method () method called in Fu");}} public class Zi extends Fu {/ * compilation [error], subclass cannot override parent private method * / @ Overrideprivate void show () {System.out.println ("show () method called in Zi") } / * compile [error], when the subclass overrides the parent class method, the access permission needs to be greater than or equal to the parent class * / @ Overrideprivate void method () {System.out.println ("the method () method in Zi is called");} / * compile [pass], when the subclass overrides the parent class method, the access permission needs to be greater than or equal to the parent class * / @ Overridepublic void method () {System.out.println ("the method () method in Zi is called") }}

It is consistent with the comments we give; therefore, we must pay attention to it in our daily programming.

2.8. Considerations for inheritance in Java

Considerations for inheritance in Java

Classes in Java only support single inheritance, not multiple inheritance.

Error example: class An extends B, C {}

Classes in Java support multi-tier inheritance

In order to better understand this knowledge point, we give the following code:

Public class Granddad {public void drink () {System.out.println ("Grandpa loves to drink");}} public class Father extends Granddad {public void smoke () {System.out.println ("Dad loves smoking");}} public class Mother {public void dance () {System.out.println ("Mom loves to dance");}} public class Son extends Father {/ / at this time, the Son class has both the drink method and the smoke method. Inheritance exercise

Requirements: define the teacher class and student class, and then write the code test; finally, find the common content between the teacher class and student class, extract a parent class, rewrite the code in the way of inheritance, and test

According to its needs, we give the following ideas:

① defines the teacher class (name, age, teaching ())

② defines the student category (name, age, study ())

③ defines test classes and writes code for testing

④ generality extract parent class to define human (name, age)

⑤ defines the teacher class, inherits human beings, and gives its own unique method: teaching ()

⑥ defines student classes, inherits human beings, and gives its own unique method: learning ()

⑦ defines test classes and writes code for testing

Through the above requirements and ideas, we implement the following code:

Package inheritExample;class Person {private String name;private int age;public Person () {} public Person (String name,int age) {this.name = name;this.age = age;} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age;}} class Teacher extends Person {public Teacher () {} public Teacher (String name,int age) {super (name,age) } public void teach () {System.out.println ("write every blog attentively");} class Student extends Person {public Student () {} public Student (String name, int age) {super (name,age);} public void study () {System.out.println ("Reader's Reading");}} class PersonDemo {public static void main (String [] args) {/ / create teacher object and test Teacher t = new Teacher (); t.setName ("the length of one calculation") T.setAge (28); System.out.println (t.getName () + "," + t.getAge ()); t.teach (); / / create student object test Student S1 = new Student ("readA", 18); System.out.println (s1.getName () + "," + s1.getAge ()); s1.study (); Student S2 = new Student ("readB", 23); System.out.println (s2.getName () + "," + s2.getAge ()); s2.study () }}

The results of the implementation are as follows:

At this point, I believe you have a deeper understanding of "how to achieve inheritance in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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