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

Example Analysis of package and inheritance of Java language

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the Java language package and inheritance example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

I. the name of the bag

Before we talk about the name of the bag, let's find out what the bag is for.

Packages (package) are allowed in Java, which organize classes in a collection. With the help of packages, you can easily manage and organize your own code, and manage your own code separately from the code base provided by others.

Packages are a way to organize classes. The main purpose of using packages is to ensure the uniqueness of the class.

In the Windows operating system, we all know that two files with the same file name cannot appear in the same folder at the same time. Our java class corresponds to a .class file, so the package is generated, and the package can actually be understood as the folder stored in the path, so each class is distributed in different packages (folders) in order to have a duplicate class name.

And the naming of the package name: the package name must be all lowercase letters, and the general package name is written in reverse order on the company's official website (domain name). If www.xxxx.com, the general package name is com.xxxx.-- and so on.

From the compiler's point of view, there is no relationship between nested packages. For example, the java.util package has nothing to do with the java.util.jar package. Each package is a separate collection of classes.

Class import and static import

A class can use all the classes in its package, as well as the common classes under other packages (public class).

There are two ways to access the class of another package:

1. Use a fully qualified name, that is, the package name is followed by the class name.

Java.util.Scanner scan = new java.util.Scanner (); / / the class name is preceded by the package name

two。 Use the import keyword

The import statement should be at the top of the source file and after the package statement.

Import java.util.Scanner;public class Main {public static void main (String [] args) {Scanner sc = new scanner ();}}

For the guide package, we also have a relatively simple way, as follows

Import java.util.*

*, which is a wildcard. That is, in the current class, you can use all the classes of the util package directly, so there is no need to import the package again. It is worth noting that the import here is not to import all the classes under the util package, which is different from the include in C language. Include in C language is everything under the import header file, while the import import here will only be imported when you need to use the classes under this package.

Of course, there is another issue to pay special attention to when importing packages for import, as follows:

Import java.util.*;import java.sql.*;public class Main {public static void main (String [] args) {Date date = new Date (); / / error, java.util.Date or java.sql.Date?}}

Compiling at this point will result in an error such as the comment section of the above code. At this point, the compiler is unable to determine which package you want to use under the Date class. You can now add a specific import to solve this problem.

Import java.util.*;import java.sql.*;import java.util.Date; / / specifically indicates that the Date class public class Main {public static void main (String [] args) {Date date = new Date ();}} under this package is used.

If you need to use the Date in both packages at this point, you can only use a fully qualified name. As follows:

Import java.util.*;import java.sql.*;public class Main {public static void main (String [] args) {java.util.Date date = new java.util.Date (); java.sql.Date date2 = new java.util.Date ();}}

Static import

We can also abbreviate the code by statically importing the package. Using import static, you can import static methods and static fields in a package. This eliminates the need to add a class name prefix.

Import static java.lang.System.*;public class Main {public static void main (String [] args) {out.println ("hello world");}}

It's just that there is a mechanism to abbreviate code, but in reality, such code may be more difficult to understand. Therefore, when you use it, you should consider it at your discretion.

Add classes to the package

If you want to put a class in a package, you must put the name of the package at the beginning of the source file, that is, before the code that defines each class in the package. As follows:

If the package statement is not written at the beginning of the source file, the class in the source file belongs to the unnamed package. The nameless bag does not have a name.

Basic rules:

Add a package statement at the top of the source file to specify which package the code is in

The package name is specified as a unique name as far as possible, usually using the company's domain name in reverse order.

The package name should match the code path. For example: package com.xxxx.demo, then the corresponding file path is com/xxxx/demo

If a source file does not have a package statement, the class is placed in an unnamed package (the default package)

IDEA package building process:

Package access

In the previous article, we introduced public and private. Private-decorated methods or member variables can only be accessed in the current class.

If there is a class that does not write public or private access modifier qualifier, then this (class, method, or member variable) can be used in other classes inside the package (under the current folder), but not in classes outside the package (under other folders). The code is as follows:

Import com.xxxx.demo1;//demo1 package public class Main {public static void main (String [] args) {Test test = new Test (); / / will report an error and insufficient access rights. }} / / = suppose the following is the file in the second folder = import com.xxxx.demo2;class Test {/ / access modifier qualifier: if it is not written, we will call it the default public int number;} public class Demo2 {public int val;}

Access modifier qualifier permissions:

Range private default (default) protectedpublic same package same YYYY same package different classes

YYY different packages, subclasses

YY different packages, different classes

Y

Among them, protected will say in inheritance, let's move on!

II. Inheritance

The basic idea of inheritance is to create a new class based on the existing class. Inheriting existing classes means reusing (inheriting) the methods of those classes, and you can add some new methods and member variables.

Classes, superclasses and subclasses

Let's start with an example, such as a cat and a dog. They have some properties such as their own name, gender, eating and so on. As shown below:

They all have their own characteristics, and we can easily find that they all have some common characteristics, such as name and gender. So if we create new cat and dog classes and have to write their own member variables, it will be repetitive and cumbersome, as shown in the following figure:

We can clearly see that the code part of the red box is exactly the same, so there is duplicate code. And both of these classes are animals, so it leads to a concept of inheritance: the "is-a" relationship.

That is to say, the concept of what is what. Inheritance may be used.

So how to implement the inheritance relationship? Let's take a look at the following picture:

We can use the extends keyword to implement the inheritance relationship, so that both the cat and dog classes can implement both the name and sex fields. This is inheritance.

At this time, cats and dogs are called subclasses or derivative classes. The Animal class is called a parent class, base class, or superclass.

Summary:

Use extends to specify a parent class

A subclass in Java can inherit only one parent class. (multiple inheritance can be implemented in C++)

The subclass inherits all the public fields and methods of the parent class

The fields and methods of the private of the parent class are inaccessible to the subclass

The instance of the subclass also contains an instance of the parent class. You can use the super keyword to get a reference to the parent class instance.

Rewrite method (override)

Like the figure above, the method name and parameter list are exactly the same in the subclass and the parent class. We call it method override. Someone may ask, how should I call the corresponding method?

We want to call the eat method of Animal. We only need to new an Animal object to call it, and of course, the same is true of the instance object of the Cat class. If we want to call the method of the parent class on the instance object of the Cat class, we can use the super keyword to call it. As shown below:

Remember:

The super keyword, when used, can only call the method or field of its immediate parent class. For example, the Animal class also inherits a class, and if super is used in the Cat class, only the methods or fields in the Animal will be called.

For a method overridden in a subclass, the level of the access modifier qualifier for this method should be higher than or equal to that of the method of the parent class. For example, the eat method in the parent class is public decorated, while the eat method in the subclass should also be public, or higher. (of course, just for example, public is the highest access modifier qualifier)

Methods that are overridden cannot be modified by static

The difference between this and super:

Subclass constructor

As mentioned above, the super keyword calls the constructor of the parent class, and exactly how it is called, let's take a look at the specific code implementation:

Public class Cat extends Animal {public Cat (String name, String sex) {super (name, sex); / / call the constructor of the parent class. The super statement must be on the first line of the subclass constructor System.out.println ("constructor of Cat");} public void eat () {System.out.println ("eat fish");}} public class Animal {public String name; public String sex The construction method of public Animal (String name, String sex) {/ / parent class this.name = name; this.sex = sex;} public void eat () {System.out.println ("eating meat");}}

Summary:

Statements that use the super constructor must be placed on the first line of the subclass constructor.

If the constructor of the parent class is not explicitly called in the subclass, the no-parameter constructor of the superclass is automatically called.

When the subclass is instantiated, the constructor of the subclass is called, and when the subclass constructor is called, the constructor of the parent class is called first. In other words, new Cat will actually create a new parent class first, and then return to the constructor of the subclass to create a new subclass after the creation of the parent class is completed.

Here is an interesting question: what is the output of the following code?

Class X {Y y=new Y (); public X () {System.out.print ("X");}} class Y {public Y () {System.out.print ("Y");}} public class Z extends X {Y y=new Y (); public Z () {System.out.print ("Z");} public static void main (String [] args) {new Z () }}

The output of the above code is: YXYZ.

Analysis:

If the subclass is called, then after entering the subclass constructor, the super statement will be executed first (if not written, the compiler comes with it), and the parent class will be constructed first.

After the construction of the parent class is complete, return to the constructor of the subclass again. The member variables of the current class will be initialized first.

The statements in the constructor are not executed until the member variables are initialized.

Appeal code execution flowchart:

Protected keyword

In the above, I wrote a table of access modifier qualifiers, the third protected keyword in the table.

Earlier, we learned about public and private access modifier qualifiers, public has a large permission, for public, the entire project can be used; for private, it can only be used in the current class. Before the two, one permission is too large and the other is too small. So this keyword is also introduced in the inheritance of Java: protected

For protected, the content decorated by protected can be used directly under this package. Under different packages, only if you inherit this class, can you use this class to be decorated by protected under different packages.

Block inheritance: final keyword

In the previous article, we introduced the final keyword, final-modified variables, which cannot be modified after initialization.

Final int a = 10 a = 20; / / compilation error occurs when an is modified by final, stored in the method area, and cannot be modified

Final can also modify a class, which means it can no longer be inherited, which is called a sealed class.

Final can also modify the method, indicating that the method cannot be overridden at this time, which is called the sealing method.

Remember: if a class is decorated with final, the method in it is automatically called final, but does not include fields. If a method is not overridden and is still short, the compiler will optimize it, a process called inlining.

Combination

Similar to inheritance, there is a concept called composition, which is also used to express the relationship between classes and to achieve code reuse.

For example, a company is made up of many people, such as managers, employees, cleaners and so on.

Class Person {public String name; public String sex;} class Manager extends Person {/ / Manager's salary public double getSalary () {}} class Staff extends Person {/ / inheritor / / salary of ordinary staff public double getSalary () {}} / / combined public class Company {public Manager [] manager; / / Manager public Staff [] staff; / / ordinary employee}

Composition does not involve a special syntax, just taking an instance of one class as a field of another class, which is also a common way or idea for us to design classes.

Combination represents the semantics of has- a: what a thing is composed of, that is, the meaning of inclusion.

Inherit the semantics of is-a: meaning: the concept of what a thing is.

Thank you for reading this article carefully. I hope the article "Java language package and inheritance sample Analysis" shared by the editor will be helpful to you. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you 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