Java object-oriented package and inheritance

Java object-oriented package and inheritance

⚡ Preface ⚡ ️
This article records the blogger's study of the object-oriented part and introduces you to the basic knowledge of Java - package and inheritance. The subsequent content will be continuously updated. (please understand that the first half of se basic grammar has not been updated due to the need to rewrite)

🍉 Blog home page: 🍁 Warm the sun like the wind🍁

🍉 Welcome to like 👍 Collection ⭐ Message comments 📝 Private letters must be answered 😁

🍉 This article was originally written by [Rufeng Wenyang], and was first launched in CSDN 🙉

🍉 Bloggers will continue to update their learning records. If you have any questions, you can leave a message in the comment area

🍉 The source code involved in the blog and the blogger's daily practice code have been uploaded Code cloud (gitee)

🍅 package

A package is a way to organize classes
The main purpose of using packages is to ensure the uniqueness of classes
For example, you write a Test class in your code Then your colleague may also write a Test class If two classes with the same name appear, they will conflict, resulting in the code can not be compiled. If a class is established in the package, the conflict of class names can be avoided

Import classes in package

Java has provided many ready - made classes for us to use for example

public class Test {
    public static void main(String[] args) { 
    java.util.Date date = new java.util.Date(); // Get a millisecond timestamp 
    System.out.println(date.getTime());
   }
}

You can use Java util. Date is introduced into Java Util is the date class in this package But this writing method is more troublesome. You can use the import statement to import the package

import java.util.Date;
public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        // Get a millisecond timestamp
        System.out.println(date.getTime());
   }
}

If necessary, use Java For other classes in util, you can use import Java util.*,* It is also called wildcard. With it, you can use all classes in the package, but unlike c/c + +, you can import all classes. Instead, you can import which class you use

import java.util.*;
public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        // Get a millisecond timestamp
        System.out.println(date.getTime());
   }
}

However, we prefer to explicitly specify the class name to be imported Otherwise, it is still prone to conflict

import java.util.*;
import java.sql.*;
public class Test {
    public static void main(String[] args) {
        // There is a class such as Date in util and sql. At this time, ambiguity will occur and compilation error will occur
        Date date = new Date();
        System.out.println(date.getTime());
   }
}
// Compilation error
Error:(5, 9) java: yes Date Ambiguous reference to
  java.sql Classes in java.sql.Date and java.util Classes in java.util.Date All match

In this case, complete class names are needed to avoid conflicts

import java.util.*;
import java.sql.*;
public class Test {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();
        System.out.println(date.getTime());
   }
}

Put the class in the package

Basic rules

  • Add a package statement at the top of the file to specify which package the code is in
  • The package name should be specified as a unique name as far as possible, usually in the inverted form of the company's domain name (e.g. com.bit.demo1)
  • The package name should match the code path For example, create com bit. Demo1 package, there will be a corresponding path com/bit/demo1 to store the code
  • If a class does not have a package statement, the class is placed in a default package
  • Package name must be lowercase

Operation steps

  1. Create a new package in IDEA: right click SRC - > New - > package
  2. Enter the package name in the pop-up dialog box, such as com bilibili. demo1
  3. Create a class in the package, right-click package name - > New - > class, and then enter the class name
  4. At this point, you can see that the directory structure on our disk has been automatically created by IDEA
  5. At the same time, we also see that in the newly created test At the top of the java file, a package statement appears

The difference between import and package

Package: "package" refers to the package where the class is located
Import: "import" refers to the class required in the imported class.
In other words, the package statement needs to be used in the package where the class is located. If a class does not have a package statement, it will also be put into a package by default. import is required because the current class needs classes in other packages.

Access control of package

We have learned about public and private in the class Members in private can only be used inside a class
If a member does not contain public and private keywords, this member can be used in other classes inside the package, but not in classes outside the package
The following code gives an example Demo1 and Demo2 are in the same package, and Test is in other packages

Demo1.java

package com.bilibili.demo1;
public class Demo1 {
    int value = 0; //Without any keyword modification, the default is package access permission
}

Demo2.java

package com.bilibili.demo1; 
public class Demo2 { 
 public static void Main(String[] args) { 
 Demo1 demo = new Demo1(); 
 System.out.println(demo.value); 
 } 
} 
// The execution result can access the value variable
10

Test.java

import com.bit.demo.Demo1; 
public class Test { 
 public static void main(String[] args) { 
 Demo1 demo = new Demo1(); 
 System.out.println(demo.value); 
 } 
} 
// Compilation error
Error:(6, 32) java: value stay com.bit.demo.Demo1 China is not public; It cannot be accessed from an external package

Common system packages

  1. java.lang: system common basic classes (String, Object). This package is from jdk1 Automatic import after 1.
  2. java.lang.reflect:java reflection programming package;
  3. java.net: network programming development kit.
  4. java.sql: support package for database development.
  5. java.util: is a tool package provided by Java. (collection class, etc.) is very important
  6. java.io:I/O programming development kit.

🍅 inherit

background

Classes created in code are mainly used to abstract some things in reality (including attributes and methods)
Sometimes there are some relations between objective things, so there will be some relations when they are expressed as classes and objects
For example, design a class to represent animals

Note that we can create a separate java file for each class Class name must be the same as Java file name matching (case sensitive)

// Animal.java 
public class Animal { 
 public String name; 
 
 public Animal(String name) { 
 this.name = name; 
 } 
 
 public void eat(String food) { 
 System.out.println(this.name + "I am eating" + food); 
 } 
} 
// Cat.java 
class Cat { 
 public String name; 
 
 public Cat(String name) { 
 this.name = name; 
 } 
 
 public void eat(String food) { 
 System.out.println(this.name + "I am eating" + food); 
 } 
} 
// Bird.java 
class Bird { 
 public String name; 
 
 public Bird(String name) { 
 this.name = name; 
 } 
 
 public void eat(String food) { 
 System.out.println(this.name + "I am eating" + food); 
 } 
 
 public void fly() { 
 System.out.println(this.name + "Flying ︿( ̄︶ ̄)︿"); 
 } 
}

We found a lot of redundant code in this code
After careful analysis, we find that Animal is related to Cat and Bird:

  • All three classes have the same eat method and behave exactly the same
  • These three classes all have the same name attribute, and the meaning is exactly the same
  • Logically, Cat and Bird are both Animal (is - a semantics)

At this time, we can let Cat and Bird inherit the Animal class respectively to achieve the effect of code reuse. At this time, the inherited class such as Animal is called parent class, base class or super class. For classes such as Cat and Bird, we are called subclass and derived class. Similar to the real children inheriting the father's property, the subclass will also inherit the fields and methods of the parent class, To achieve the effect of code reuse.

rule of grammar

Basic grammar

class Subclass extends Parent class { 
}
  • Use extends to specify the parent class
  • A subclass in Java can only inherit one parent class (while languages such as C++/Python support multiple inheritance)
  • When constructing a subclass, you should first construct the parent class
  • Subclasses inherit all public fields and methods of the parent class (the construction method will also inherit, but it is troublesome)
  • private fields and methods of the parent class are inaccessible in subclasses (you can also inherit but cannot access)
  • Instances of subclasses also contain instances of parent classes You can use the super keyword to get the reference of the parent class instance

The above code can be improved by inheritance At this point, we let Cat and Bird inherit from the Animal class, so Cat doesn't have to write the name field and eat method when defining

class Animal { 
 public String name; 
 public Animal(String name) { 
 this.name = name; 
 } 
 public void eat(String food) { 
 System.out.println(this.name + "I am eating" + food); 
 } 
} 
class Cat extends Animal { 
 public Cat(String name) { 
 // Use super to call the constructor of the parent class. If there is no constructor in the parent class, it can not be constructed
 super(name); //It can be understood that both son and father have the attribute of name
 } 
} 
class Bird extends Animal { 
 public Bird(String name) {
  super(name); 
 } 
 public void fly() { 
 System.out.println(this.name + "Flying ︿( ̄︶ ̄)︿"); 
 } 
} 
public class Test { 
 public static void main(String[] args) { 
 Cat cat = new Cat("Xiao Hei"); //It can be understood that both the son and the father have the attribute of name, but the name "Xiaohei" is given to the son.
 cat.eat("Cat food"); 
 Bird bird = new Bird("round"); 
 bird.fly(); 
 } 
}

The original English meaning of extends is "extension" The inheritance of the class we write can also be understood as the "extension" of the code based on the parent class
For example, the Bird class we wrote extends the fly method on the basis of Animal

If we change the name to private, the subclass cannot be accessed at this time

class Bird extends Animal { 
 public Bird(String name) { 
 super(name); 
 } 
 public void fly() { 
 System.out.println(this.name + "Flying ︿( ̄︶ ̄)︿"); 
 } 
} 
// Compilation error
Error:(19, 32) java: name stay Animal Medium is private access control 

protected keyword

Just now we found that if the field is set to private, the subclass cannot be accessed However, setting it as public violates our original intention of "encapsulation" The best of both worlds is the protected keyword

  • The fields and methods modified by protected are inaccessible to the caller of the class
  • The fields and methods modified by protected are accessible to subclasses of a class (which may or may not be the same package) and other classes of the same package
// Animal.java 
public class Animal { 
 protected String name; 
 public Animal(String name) { 
 this.name = name; 
 } 
 public void eat(String food) { 
 System.out.println(this.name + "I am eating" + food); 
 } 
} 
// Bird.java 
public class Bird extends Animal { 
 public Bird(String name) { 
 super(name); 
 } 
 public void fly() { 
 // For the protected field of the parent class, the child class can access it correctly
 System.out.println(this.name + "Flying ︿( ̄︶ ̄)︿"); 
 } 
} 
// Test.java and animal Java is not in the same package 
public class Test { 
 public static void main(String[] args) { 
 Animal animal = new Animal("Small animals"); 
 System.out.println(animal.name); // At this time, there is a compilation error and name cannot be accessed 
 } 
}

Summary: there are four access permissions for fields and methods in Java

  • private: it can be accessed inside the class, but not outside the class
  • Default (also called package access permission): it can be accessed inside a class. Classes in the same package can be accessed, but other classes cannot
  • protected: it can be accessed inside a class. Subclasses and classes in the same package can be accessed. Other classes cannot be accessed
  • public: both inside the class and the caller of the class can access it

When and which one?
We hope that the class should be "encapsulated" as much as possible, that is, hide the internal implementation details and only expose the necessary information to the caller of the class
Therefore, we should use strict access rights as much as possible For example, if a method can use private, try not to use public
In addition, there is a simple and crude approach: set all fields to private and all methods to public However, this method is an abuse of access rights, or do you want students to think carefully when writing code about who to use the field methods provided by this class (whether they are used by the class itself, the caller of the class, or the subclass)

More complex inheritance relationships

In our example just now, only Animal, Cat and Bird are involved But what if the situation is more complicated? In this case, we may need to represent more kinds of cats

In this case, there will be more complex inheritance relationships. Generally, we don't want more than three layers of inheritance relationships If there are too many inheritance levels, you need to consider refactoring the code If you want to restrict inheritance from syntax, you can use the final keyword

final keyword

We once learned that when the final keyword modifies a variable or field, it represents a constant (which cannot be modified)

final int a = 10; 
a = 20; // Compilation error
final Keywords can also modify classes, At this point, the modified class cannot be inherited.
final public class Animal { 
 ... 
} 
public class Bird extends Animal { 
 ... 
} 
// Compilation error
Error:(3, 27) java: Can't start from the end com.bit.Animal Inherit

The function of the final keyword is to restrict the class from being inherited. The "restriction" means "inflexible" In programming, flexibility is often not a good thing Flexibility may mean more error prone
When the class decorated with final is inherited, it will compile and report an error. At this time, it can remind us that such inheritance is contrary to the original intention of the class design
The String class we usually use is decorated with final and cannot be inherited

⭐ Last words ⭐ ️

It's not easy to summarize. I hope uu you won't be stingy with your work 👍 Yo (^ u ^) yo!! If you have any questions, please comment and correct them in the comment area 😁

Keywords: Java Back-end JavaSE

Added by alarik149 on Sun, 30 Jan 2022 06:02:40 +0200