Java Lecture 6: Package import access modifiers final and static, static code blocks and image loading methods

Table of Contents

1. Package

2. import (import) keyword

3. Access modifiers

3. final keyword

4. static keyword

5. How to load images

1. Package

If there is no package, a large project may need to create many, many class files. If the class name is a unique identifier, file name conflicts are likely to occur.

It would be too troublesome to think of 1,000 class names for 1,000 classes, so Java designed packages.

Function: Avoid class name conflicts

Phenomenon: Class names in the same package cannot conflict, and class names in different packages have no effect.

Package name: Requires pure lowercase (standard), the package name must be written in reverse order according to Domain name. Project name. Module name. Class name

Write the domain name in reverse: For example, www.baidu.com, then write it in reverse as com.baidu

Project name: such as submaring

Module name: The company will specify

Full package name of the class: reverse domain name.Project name.Module name.Class name

2. Import (import) keyword

When do you need to use import:

1. The class that needs to be used currently is not in the same package, so you need to import the full package name of the class through import before it can be used.

Sometimes you don’t know where to find this package. Just move the mouse to the class name, then alt + enter + enter, and you can directly import it automatically.

2. Under the same package, there is no need to guide the package, just use it directly.

When using some functions provided by java, some packages cannot be used without importing the package.

3. Access modifier

Method encapsulation: Encapsulate repeated business logic into methods to achieve reuse.

Class encapsulation: Encapsulate the properties and behaviors common to multiple objects under a category into a template class.

Attribute encapsulation: used to hide some content from complete external access. If accessed, it can also be used by the other party conditionally. Ensure the robustness, legality, and security of the program.

Private attributes and make methods public (more important attributes cannot be directly accessed by the outside world. If the outside world wants to access them, they need to access them through the corresponding attribute get (get) / set (set) methods)

Access modifiers can modify our classes (generally not needed, generally public by default), methods, and properties.

1. Public: Public, with the greatest access rights, and can be accessed from any location. (Can be called anywhere)

2.private: Private, with the smallest access rights, only the current class content is available. (Cannot be accessed anywhere else)

This is to prevent modification and protect the current attributes.

3. Default: No need to write any modifiers. Access permissions can be accessed by this class and classes in the same package. (something you often do)

4. protected: protected, the access rights are in this class. The same package class and subclasses of different packages can access it. Generally used in parent classes of inheritance relationships.

Example:

class Wife{ //Wife class
   private String name = "Wang Xiaohua"; //Attribute privatization
   private int age = 18; //Attribute privatization
    
   public String getName(){//Make the method public
       return "Wang Xiaohua";
   }
   
   public void setAge(int age){//Make the method public
       if(age < 25 & amp; & amp; age >18){
           this.age = age;
       }
   }
}
?
Wife w = new Wife();

(Important) For detailed access modifier ranges, please refer to the table below:

Access modifier Internal class Same package class/subclass Non-same package subclass Non-same package class
 public √ √ √ √
 protected √ √ √
 Default √ √
 private √

4. final keyword

Can modify methods, classes and properties

represents the final meaning

It is also used to modify class members.

You just need to know what characteristics it will have after retouching.

placed after the access modifier

1. Modified attributes: Attributes modified with final cannot be modified twice! And when declaring a final attribute, the assignment must be initialized

You cannot declare first and then assign a value, you must do it at the same time!

2. Modification method: The method modified with final cannot be rewritten! Generally used in parent class level code. There are some functions that can be used when you don’t want subclasses to inherit.

3. Modified classes: Classes modified with final cannot be inherited! It is equivalent to cutting off descendants and putting it in front of the class name.

If it is inherited, there is a risk of being modified.

Example:

package oo.day03;
?
/**
 * The final test uses the demo class:
 */
public class FinalDemo {
    public int a;//Ordinary member variables do not require initialization and assignment
    public final int b = 100;//Variables declared final require initialization and assignment.
    public void fun(){
        a = 10;
        a = 200;
// b = 500; Variables modified with final cannot be modified twice.
    }
}
final class Aoo{ //final modified class
   public final void sayHi(){ //final modified method
?
    }
}
class Boo extends Aoo{ //Subclasses modified by final cannot be inherited
// public void sayHi() {//The method modified by final cannot be overridden
//
// }
}
?

5. static keyword

Each person is equivalent to each object. The cup in his hand belongs to the individual and belongs to the object.

Do the drinking fountains in the teaching building belong to the target group? Does not belong to the object, but is shared by the object.

So it can be understood that static is the attributes and methods of the class. The static keyword can only be used to modify class properties and methods.

variable:

1. Instance variables: Member variables are instance variables (actually attributes).Instance variables belong to objects! (There are as many copies of data as there are objects), stored in the heap. Accessed through objects.

2. Static variables: Variables modified with static are called static variables, which belong to the class (and there is only one)! Use classes to make calls.

In fact, you can also make point calls by instantiating objects (but from the perspective of the code writing structure, this is not supported)

When a class is used for the first time, the .class bytecode file corresponding to the class will be loaded into the method area. Note that it will only be loaded once!

JVM divides memory areas:
                stack area, heap area, method area
    1. Place local variables in the stack area
    2. Place objects in the heap
    3. Method area: An area used to load .class bytecode files (methods and static methods/constructors/static variables in the class). 

Sample code:

package oo.day03;
?
/**
 * Static usage demonstration class:
 */
public class StaticDemo {
    public static void main(String[] args) {
        Coo c1 = new Coo();
        c1.show();
        Coo c2 = new Coo();
        c2.show();
        Coo c3 = new Coo();
        c3.show();
    }
}
class Coo {
    int a;//Properties --->Member variables---->Instance variables! Belongs to the object! Each object has its own independent
    static int b;//Static variables belong to the class! Only one copy is shared by the current class object
    Coo() {
        a + + ;
        b + + ;
    }
    void show() {
        System.out.println("The data of a is: " + a + ", the data of b is: " + b);
    }
}
?

In the code above, the value of b will automatically increase every time it is run.

So in fact, the static keyword makes the attribute a shared attribute of the class, rather than an instance variable.

Static applicability:

When there is a piece of data that needs to be shared by all objects under a certain category, the data can be made static.

Example:

When there is a mine submarine picture that needs to be used by a mine submarine class object, this picture can be made into a static resource.

Can save memory

Static methods:

1. Methods modified with static are called static methods. If it belongs to a class, it is called through the class name.

2. Stored in the method area.

3. The content of static methods is not passed implicitly this! Unable to access instance member!

It can be understood that static methods are methods of the class, so the parameters that appear in the static method should be parameters in the class, not parameters of the instance (this. attribute), because the class cannot access instance members.

So in the following code, why do we create an action method and instantiate the attributes of gameworld in it? It is because the attributes of gameworld are all instance variables of gameworld, and the main method is static and can only be accessed Class methods and class static properties cannot access instance variables! ! So we wrote a class action method here, and called it through class management to instantiate the submarine, bomb, etc. classes in the gameworld.

public class GameWorld extends JPanel {//The current test class inherits JPanel
    Battleship ship; //Declare a variable of battleship type
    Bomb[] bombs;//Declare a variable of depth bomb array type
    SeaObject[] submarines;//Represents three types of submarines (reconnaissance submarines, mine submarines, torpedo submarines)
    SeaObject[] thunders;//Represents two types of mines (mines, torpedoes)

    void action() {
        ship = new Battleship();//Create a battleship object for the battleship class and store it in the ship variable
        submarines = new SeaObject[9];

    public static void main(String[] args) {
        GameWorld gw = new GameWorld();
        gw.paintWorld();//Call the method of drawing the window
        gw.action();
    }

Applicability: Static methods are suitable for tool content logic. The purpose is to facilitate external use and can be used directly through the class name point. Equivalent to encapsulation, it can call methods without implementing an instance.

For example, Math.random() is calling the random method of the Math class. If you don’t want others to change this method, use static.

static void test() {//In static methods, there is no implicit this passed! All members of the instance (instance variables, ordinary methods) cannot be accessed in static methods.
                                    //Error reported, no this is passed.
    // System.out.println("The data of a is: " + this.a + ", the data of b is: " + Coo.b);
?
}

Project thinking: Many categories in the project have corresponding pictures. For example: all objects under the reconnaissance submarine category require a reconnaissance submarine picture. If the pictures under each category want to be shared by the corresponding category, they need to be made into a static image type.

Design principle: The class has a single responsibility. For the current image loading operation, we should make a separate class for loading all images in the project.

So here we create an ImageResources class file, and use this class to load the resources used in the game.

Static code block:

Grammar structure:
To be written in the class

static{

}

1. A code block modified with static is called a static code block

2. Belonging to a class, the static code block will also be executed when the current class is loaded for the first time. Will only be executed once.

3. If there are static code blocks and construction methods when creating a class object, the contents of the static code block will be executed.

4. Even if the class accesses static members, if it is the first time the class is used, it will be loaded.

package oo.day03;
?
/**
 * Static usage demonstration class:
 */
public class StaticDemo {
    public static void main(String[] args) {
        Coo.b = 10; //When the class is used, it will be loaded into the method area. The static code block of the corresponding class will be executed
        new Coo();
    }
}
class Coo {
    int a;//Properties --->Member variables---->Instance variables! Belongs to the object! Each object has its own independent
    static int b;//Static variables belong to the class! Only one copy is shared by the current class object
    Coo() {
        System.out.println("Constructor of class Coo");
    }
    static {//Static code block
        System.out.println("Coo class static code block was executed");
    }
?
}
?

6. How to load images

Create an image loading resource class under the project package:

ImageResource

package cn.tedu.submarine;
?
import javax.swing.*; (You don’t need to import it yourself, just type an ImageIcon to realize automatic import)
?
/**
 * Image resource loading class:
 * Responsible for loading and initializing the images required in the project
 * */
public class ImageResources {
    //ImageIcon is the type used to store image resources
    //1. Declare first
    public static ImageIcon battleShip;//Variable used to store battleship images
    public static ImageIcon bomb;//Variable used to store images of depth bombs
    public static ImageIcon gameover;//Variable used to store the game over image
    public static ImageIcon mine;//Variables used to store mine images
    public static ImageIcon minesubm;//Variables used to store images of mine submarines
    public static ImageIcon obsersubm;//Variables used to store images of reconnaissance submarines
    public static ImageIcon sea;//Variables used to store ocean background images
    public static ImageIcon start;//Variable used to store the game start image
    public static ImageIcon torpedo;//Variable used to store torpedo images
    public static ImageIcon torpedosubm;//Variables used to store torpedo submarines
    //2. Assignment
    static{//Static code block When the class is loaded, the content in the code block is executed.
        battleShip = new ImageIcon("img/battleship.png");
        bomb = new ImageIcon("img/bomb.png");
        gameover = new ImageIcon("img/gameover.png");
        mine = new ImageIcon("img/mine.png");
        minesubm = new ImageIcon("img/minesubm.png");
        obsersubm = new ImageIcon("img/obsersubm.png");
        sea = new ImageIcon("img/sea.png");
        start = new ImageIcon("img/start.png");
        torpedo = new ImageIcon("img/torpedo.png");
        torpedosubm = new ImageIcon("img/torpesubm.png");
    
    }
?
}

1. Declare variables

2. Assignment (because ImageIcon is a class), so here directly instantiate an ImageIcon and assign it to battleship, and the path (relative path) is in parentheses.

3. The static keyword is used here to execute the content in the code block every time the class is loaded or every time an instance of the class is called. Achieve repeated display of pictures.

4. And! After this, each image variable needs to be printed out. If the result is 8, it means the image can be loaded normally. If it is 4, it means there is an error in the variable and you need to check the code to ensure that the image can be displayed normally.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138929 people are learning the system