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

Sample Analysis of package and inheritance in Java

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

Share

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

This article will explain in detail the example analysis of package and inheritance in Java. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

1. Bag 1. Concept

By definition: packages are a way to organize classes

So why organize classes?

To put it simply, it is to ensure the uniqueness of the class, for example, in the future work, if you develop a project together, you may write a Test class in your own code, and if there are two classes with the same name, it will conflict and the code will not be compiled through.

Understand it with a piece of code

Import java.util.*;public class TestDemo {public static void main (String [] args) {/ / get a millisecond timestamp Date date=new Date ();}}

The above code imports the util package and uses the Date class in it to get a millisecond timestamp. And if we import another sql package,

Import java.sql.*;import java.util.*;public class TestDemo {public static void main (String [] args) {/ / get a millisecond timestamp Date date=new Date ();}}

The above code will compile an error, showing Reference to 'Date' is ambiguous, both' java.sql.Date' and 'java.util.Date' match, that is, there are Date classes in both packages, and you don't know which one to match. Make a slight modification to determine who the Date matches, as shown in

Java.util.Date date=new java.util.Date ()

Or you can modify it here.

Import java.sql.*;import java.util.Date;2. Mode of use

Many off-the-shelf classes have been provided in Java for us to use, such as the Date class in the above code, as well as the Scanner class, Arrays class, and so on that we often use.

And these classes are placed in various packages, for example, there are many common classes in the util package.

Although there are so many wrapped classes for us to use in Java, we can't use them directly.

Some of the classes in the lang package can be used directly, such as String, Short, Byte, Float, etc. (because these classes are automatically imported), write a code to understand

Public class TestDemo {public static void main (String [] args) {/ / output the maximum long System.out.println (Long.MAX_VALUE);}}

The above code is the maximum value of the output long type, where the Max_VALUE method of the Long class is used. And there is no need to manually import the lang package.

Other packages need to be imported manually when they are used, and there are generally the following methods of import.

Method 1: when using it directly, add the package name before the class, such as

Public class TestDemo {public static void main (String [] args) {/ / get a millisecond timestamp java.util.Date date=new java.util.Date ();}}

This way of writing is troublesome and not concise.

Method 2: import a class in a package directly using the impot statement, such as

Import java.util.Date;public class TestDemo {public static void main (String [] args) {/ / get a millisecond timestamp Date date=new Date ();}}

Note:

When importing a package, you can also use the * * wildcard character * * directly to import everything in the util package, such as

Import java.util.*

But this does not directly import all the classes in the package, but the class you use will import the class.

However, if both imported packages use wildcards and both packages contain classes of the same name, errors will occur when using them, such as

Import java.sql.*;import java.util.*;public class TestDemo {public static void main (String [] args) {/ / get a millisecond timestamp Date date=new Date ();}}

Therefore, it is more recommended to import a specified class

Method 3 (explained below, not often used): static import

Knowing this, import in Java is very different from # include in C++, which must use # include to bring in other file contents, but Java does not.

3. Static import

In fact, static methods have been mentioned in the previous chapter on methods, and static imports, like static methods, are modified by the keyword static and import packages using import static.

Static import allows us to avoid writing class names, which is more convenient at some times, such as

Import static java.util.lang.Math.*;public class TestDemo {public static void main (String [] args) {double Xero3; double ans=pow (XMagne2);}}

In fact, the pow method omits the class name Math.

4. Create a package

Now that we understand the package in Java, can we create a package ourselves? Because in this way, we can use the same class name when developing with others!

Basic rules:

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

The package name should match the code path

If a class does not have a package statement, it will be placed in a default package

The package name should be in all lowercase and be specified as a unique name as far as possible (generally named as follows)

Personal project: pers. The name of the initiator. Project name. Model fast name

Team project: pers. Name of the team. Project name. Model fast name

Company project: com. Name of the company. Project name. Model fast name

In order to facilitate the understanding of the above rules, let me create a package manually.

Create and use steps:

Right-click src, click new, and select create a package

Create a package name, all lowercase

We can see this after creation, and the package name is the same as the path of the code

Click demo1 to create a Java file

Have you noticed that I have created a class called TestDemo, which is already in src. That's what bags are for! And this file has package pers.dmw.demo1; that specifies the location of the code.

Use the class you created

When we type Test, it shows two TestDemo, which is the class we created. According to what we have learned above, import the package before using this class

It's done!

5. Access to the package

In previous classes, we learned about public and private, in which members modified by public can be used throughout the project, while members modified by private can only be used in their own classes

Members that are not modified by both can be used in other classes of this package, but not in other packages

For example, two classes TestDemo1 and TestDemo2 are defined in the package created by us, while TestDemo is defined in other packages

The TestDemo2 code is as follows

Package pers.dmw.demo1;public class TestDemo2 {public int axi10; private int bread20; int cantilever 30;}

The Testdemo1 code is as follows

Package pers.dmw.demo1;public class TestDemo1 {public static void main (String [] args) {TestDemo2 testDemo2=new TestDemo2 (); System.out.println (testDemo2.a); System.out.println (testDemo2.b); System.out.println (testDemo2.c);}}

Where b cannot be printed because it is modified by private and can only be used in its own class

The TestDemo code is as follows

Package pers.dmw.demo1;public class TestDemo {public static void main (String [] args) {TestDemo2 testDemo2=new TestDemo2 (); System.out.println (testDemo2.a); System.out.println (testDemo2.b); System.out.println (testDemo2.c);}}

Neither b nor c can be printed. B is a class decorated by private, while c is not modified and can only be used in its own package.

6. Common system packages

The general knowledge of the package has been introduced, and finally let's take a look at those common system packages.

Java.lang: the basic classes commonly used in the system (String, Object). This package is automatically imported from JDK1.1.

Java.lang.reflflect:java reflection programming package

Java.net: network programming Development Kit

Java.sql: a support package for database development

Java.util: a tool package provided by Java

Java.io:I/O programming development kit

II. Inheritance

We know that the basic characteristics of object-oriented are inheritance, encapsulation and polymorphism.

We've learned about encapsulation, and then we're going to learn about inheritance.

Before we learn inheritance, let's first recall classes and objects. Before I gave an example of laundry, friends who don't remember can take a look at the previous text Java basic syntax to help you understand classes and objects.

And today I'm going to use a riddle to better help you understand classes and objects.

Riddle:

Young, with a beard. When the guests come, call your mother (hit an animal)

Answer the riddle:

Ah!? Guess first. I have put the answer to the riddle at the end of this chapter. The friends who have finished guessing can go below to verify it.

We can find out

A riddle is an abstraction.

The answer to the riddle is a specific.

Class is the abstraction of a thing.

An object is an abstract concrete.

After reviewing classes and objects, we began to learn about inheritance, so what is inheritance?

1. Concept

In fact, the inheritance here is very similar to the inheritance in our lives, such as who inherits the estate of the elders. We can also use this metaphor to write a code.

First, let's look at a picture.

There is a sheep and a wolf in the picture, and then they all belong to animals, right? then we can write a category according to animals.

Class Animal {public String name; public int age; public void eat () {System.out.println ("I'm going to sleep!") ;} public void bark () {System.out.println ("I'm going to scream") ;}}

In this class, the name of the animal, the age attribute and the behavior of sleeping and barking are defined. Let's continue to define a class for wolves and sheep.

Wolf

Class Wolf {public String name; public int age; public void eat () {System.out.println ("I'm going to sleep!") ;} public void bark () {System.out.println ("I'm going to scream") ;} public void hunt () {System.out.println ("I want to hunt!") ;}}

Sheep

Class Sheep {public String name; public int age; public int cleatNum; public void eat () {System.out.println ("I'm going to sleep!") ;} public void bark () {System.out.println ("I'm going to scream") ;}}

We find that in the definition of the class of sheep and wolf, because they all belong to animals, they have some attributes and behaviors of animals, so we can make the code of the class of sheep and wolf more brief through inheritance.

Wolf

Class Wolf extends Animal {public void hunt () {System.out.println ("I want to hunt!") ;}}

Sheep

Class Sheep extends Animal {public int cleatNum;}

For example, An extends B in the above code is inheritance. Among them

A: call it a subclass or a derived class

B: it's called a parent class, base class, or superclass.

When the subclass inherits the parent class, the subclass has the methods and properties of the parent class

So the meaning of inheritance is

For the reuse of the code

The idea of inheritance is

Extract the commonness and put it into the base class

Extends

two。 Syntax rules (including super usage)

Here we will introduce the grammar rules of inheritance in more detail in order to solve some doubts.

Syntax:

Class subclass extends parent class {}

Rules:

A subclass in Java can inherit only one parent class (languages such as C++/python support multiple inheritance)

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

For fields and methods of the private of the parent class, the subclass cannot access (can inherit)

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

Note:

Since there is only single inheritance in Java, in order to solve this problem, we can implement a relationship similar to "multi-inheritance" through interfaces.

So what does the above keyword super mean? First of all, let's look at this piece of code.

Class Animal {public String name; public void eat () {System.out.println (this.name + "going to bed!") ;} public void bark () {System.out.println (this.name + "here we go!") ;}} class Wolf extends Animal {public void hunt () {System.out.println (this.name + "time to hunt!") ;} public class TestDemo {public static void main (String [] args) {Wolf wolf=new Wolf (); wolf.name= "Grey Wolf"; wolf.eat (); wolf.bark (); wolf.hunt ();}}

This is a simple subclass that inherits the use of the parent class.

We know that creating an object consists of two steps: allocating memory to the object and calling the construction class. When we do not define a constructor, the system will automatically construct a no-parameter constructor for us.

So if we actively create a constructor in the parent class

Class Animal {public String name; public Animal (Stirng name) {this.name=name;} public void eat () {System.out.println (this.name + "going to bed!") ;} public void bark () {System.out.println (this.name + "here we go!") ;}}

Then we have to remember that the subclass inherits the parent class and needs to help the parent class construct first. So how to construct it, you have to use super.

Class Wolf extends Animal {public Wolf (String name) {super (name); / / calls the constructor of the parent class} public void hunt () {System.out.println (this.name + "I'm going to hunt!") ;}}

Super calls the constructor of the parent class, which satisfies that the constructor of the parent class should be constructed before the subclass inherits the parent class.

Let's take a look at super:

Super: represents a reference to the parent class of the current object (but this argument is not rigorous, this is the conclusion of the analogy with this)

Super (): calls the constructor of the parent class

Super. Parent attributes: calling the properties of the parent class

Super. Parent method: call the method of the parent class

Note:

When we don't actively create constructors, isn't there a constructor that the system actively creates? Because when we do not take the initiative to create it, the system also actively uses super.

Super cannot be used with this because they are all on the first line

Super cannot be used in a method modified by static because it depends on the object

Super only points to the most direct parent class, not to the parent class

3. Protected keyword

By comparing the previously learned keywords public, private, default, and the coming keyword protected, we can get the following table

Num scope private default (package access) protectedpublic1 same class in the same package ✔✔✔✔ 2 different classes in the same package

Subclasses in different packages of ✔✔✔ 3

Non-subclasses in different packages of ✔✔ 4

We found that in the above code, when I used inheritance, the properties of the parent code were decorated with public. In this way, subclasses can use these properties normally, but this violates the idea of "encapsulation". But if decorated with private, the subclasses of different packages cannot be accessed

So a keyword protected appears, and if you use it,

For non-subclasses of different packages: protected-decorated fields and methods are not accessible

For subclasses of different packages and other classes of the same package: protected-decorated fields and methods are accessible

At this point, we can begin to solve some previously unmentioned problems: if both the parent class and the child class have the same parameter, which one should be used in the call? Let's look at the following code

Class Base {public int astat1;} class Derieve extends Base {public int astat3; public void func () {System.out.println (a);}} public class TestDemo {public static void main (String [] args) {Derieve derieve=new Derieve (); derieve.func ();}} / / the result is: 3

In other words, the call also relies on a nearest principle, which defaults to that in the subclass. So what if you want to call the parent class when you call it? At this point we can use super to invoke the properties of the parent class. Just change the Derieve class to this.

Class Derieve extends Base {public int astat3; public void func () {System.out.println (super.a);}} / / result: 1

As for the problem of the same name of the method, it will be explained in the next chapter!

4. More complex inheritance relationships

The above inheritance relationships are relatively simple, if the relationship becomes more complex, such as this, what should we do?

Emmm, in fact, the general recommendation is not to exceed the three-tier inheritance relationship, if there are too many inheritance levels, you need to consider refactoring the code.

Sometimes we write a lot of inheritance relationships before we know it, so in order to restrict inheritance in syntax, we can use the keyword final

5. Final keyword

We have seen final before, which can modify a variable or field so that it becomes constant and cannot be modified, such as

Final int axi10umbent / an is constant and cannot be modified

Here, final can also modify the class, so the modified class cannot be inherited and is called a sealed class, such as

Final class A {}

At this point, A cannot be inherited.

Final can also modify the method, the modified method is called sealing method, as for the role of final at this time, the next chapter will explain!

III. Combination

The above emphasis explains the content related to inheritance, and the meaning of inheritance is to make the code reusable.

Composition is also a way to express the relationship between classes, and can also achieve the effect of code reuse.

As the name implies, combination is to combine all kinds of things into one thing. For example, learning, the school is made up of teachers, students, teaching buildings and so on. We can write a code.

Class Teacher {/ /...} class Student {/ /...} public class School {public Teacher [] teachers; public Student [] students;}

The above code encapsulates the teacher and student's class into an object and acts as a field of another class.

This is the end of this article on "sample Analysis of package and inheritance in Java". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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