[For beginners] Explanation of classes, instances, and statics in Java

About this material

We are training Java using "Introduction to Java that is refreshingly understood, 2nd edition". I think this book is pretty straightforward, but it's still an object-oriented explanation, and it seems that it's often not hungry when it comes to "instances."

The book states:

"If you think that the class is the same as the" mold "in the plastic model factory ..." (P.302) "It is" * instance * "that operates in the virtual world, and the mold for creating that instance is" * class * ". (P.303)

Note: The term "virtual world" here means JVM. (P.283)

It's an abstract story, so I think it's a good way to get an image. However, when it comes to actually using it, I think it needs a little more specific explanation.

Target audience of this commentary

It is intended for the following people.

--Beginners learning Java. --Those who have learned about instances and statics, but are not comfortable with them. --Especially those who are studying Part II of "Introduction to Java that can be understood clearly 2nd edition" (hereinafter referred to as "book").

Purpose and scope of this material

The purpose is to give you an overview of how the JVM works in memory and to give you a better understanding of how to code it.

--Class

The following items are excluded.

--Encapsulation, access modifier

Commentary

1. Class loading

The class is loaded into the JVM's memory when it is to be used by the application. Programmers don't have to worry because Java loads the classes.

Cleric.java


class Cleric {
    private String name;
    private int hp;

    public Cleric(String name, int hp) {
        this.name = name;
        this.hp = hp;
    }
    public String toString(){
        return this.name + " HP:" + this.hp;
    }
}

↑ Image ↓ Class1.png

With this alone, you can only load the class and not the members. This is because it is not instantiated, only name and hp are defined, and neither name nor hp is allocated in memory.

2. Instantiation

Let's use new.

ClericQuest.java


class ClericQuest {
    public static void main(String[] args) {
        Cleric cleric1 = new Cleric("John", 50);//New here
        System.out.println(cleric1.getName());//Access the new instance
    }
}

↑ Image ↓ Class2.png By doing new, the instance will be secured in the memory of the JVM. Members are also in it. Now you can use name and hp as well.

You can create multiple instances.

ClericQuest.java


class ClericQuest {
    public static void main(String[] args) {
        Cleric cleric1 = new Cleric("John", 50); //The first new
        Cleric cleric2 = new Cleric("Taro", 55); //Second new
        Cleric cleric3 = new Cleric("Mary", 65535); //Third new
        System.out.println(cleric1);
        System.out.println(cleric2);
        System.out.println(cleric3);
    }
}

↑ Image ↓ Class3.png

Members of each instance are allocated separately in memory. In this example, the name of cleric1 does not affect the name of cleric2.

3. What about static?

The above omits the explanation of static, so we will explain static.

static is translated as "static". It is reserved from the beginning and cannot be increased or decreased. On the other hand, "dynamic" means that it can be increased or decreased at will. The explanation so far has been about dynamic members (= non-static members) that can increase the number of instances by new.

Static members are allocated in the JVM's memory when the class is loaded.

Cleric.java


class Cleric {
    private String name;
    private int hp;
    private static int countMember = 0; //The number of instances of the Cleric. static

    public Cleric(String name, int hp) {
        this.name = name;
        this.hp = hp;
        Cleric.countMember ++;
    }
    public String toString(){
        return this.name + " HP:" + this.hp;
    }
    public static int getCountMember(){
        return Cleric.countMember;
    }
}

ClericQuest.java


class ClericQuest {
    public static void main(String[] args) {
        System.out.println("The number of people" + Cleric.getCountMember());//0 is displayed
        Cleric cleric1 = new Cleric("John", 50);
        Cleric cleric2 = new Cleric("Taro", 55);
        Cleric cleric3 = new Cleric("Mary", 65535);
        System.out.println(cleric1);
        System.out.println(cleric2);
        System.out.println(cleric3);
        System.out.println("The number of people" + Cleric.getCountMember());//3 is displayed
    }
}

↑ Image ↓ Class4.png

Instantiation does not increase static members.

As a result, static members have the following characteristics:

  1. Not tied to an instance. Associate only with the class.
  2. Can be used without instantiation (new).
  3. Shared by all instances.
  4. Non-static members are not (directly) available from static methods.
  5. Cannot inherit. (It is possible to define the same name in a subclass, but it is irrelevant.)

Supplement

FAQ (questions that are likely to be asked)

If static isn't tied to an instance, does it make sense to put it in a class? → When you think about class design such as encapsulation, it makes sense to make it a member of the class.

It says "1. It is not tied to an instance", but is it consistent with "3. It is shared by all instances"? → Since "1. It is not linked to the instance", if it is set to public static, it will be shared by the entire program, but if it is set to private static, it can be accessed only from the same class, so it is described like this.

It says "1. It is not tied to an instance", but you can write it as "instance". "Static member name". → The description "instance". "Static member name" does not cause a compile error, but it is not correct. Should be "class name". "Static member name". (Of course, if it is your own class, you do not need the class name part.)

You're not using toString, right? → It's fun for future study.

By the way

I think understanding the instance is one of the early stumbling blocks. If you understand this, you can understand other Java-like programming languages.

I'm talking about classes and instances, but I think understanding static will help you better understand instances.

Recommended Posts

[For beginners] Explanation of classes, instances, and statics in Java
Classes and instances Java for beginners
java (classes and instances)
Kantai Collection Java # 1 Classes and Objects [For Beginners]
[For beginners] DI ~ The basics of DI and DI in Spring ~
Java classes and instances to understand in the figure
List of frequently used Java instructions (for beginners and beginners)
[For beginners] Summary of java constructor
Rock-paper-scissors game for beginners in Java
Java for beginners, expressions and operators 1
[For beginners] Run Selenium in Java
Java for beginners, expressions and operators 2
Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~
[Java] for Each and sorted in Lambda
[For beginners] Difference between Java and Kotlin
Java programming (classes and instances, main methods)
Explanation of Ruby on rails for beginners ①
Discrimination of Enums in Java 7 and above
Classes and instances
I wrote EX25 of AtCoder Programming Guide for beginners (APG4b) in java.
About the idea of anonymous classes in Java
[Java] Personal summary of classes and methods (basic)
Differences in writing Java, C # and Javascript classes
Basics of threads and Callable in Java [Beginner]
A collection of simple questions for Java beginners
[Introduction to Java] Basics of java arithmetic (for beginners)
[Ruby] Classes and instances
java classes, instances, objects
About classes and instances
Ruby classes and instances
[For beginners] Quickly understand the basics of Java 8 Lambda
About the difference between classes and instances in Ruby
[For beginners] Minimum sample to display RecyclerView in Java
Usability of date and time classes in each language
Introduction to Java for beginners Basic knowledge of Java language ①
This and that for editing ini in Java. : inieditor-java
Use of Abstract Class and Interface properly in Java
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ② ~ Creating links ~
Equivalence comparison of Java wrapper classes and primitive types
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
Explanation of Ruby on rails for beginners ④ ~ Naming convention and how to use form_Tag ~
A brief explanation of a maze game made in Java for a cousin of an elementary school student
Store in Java 2D map and turn with for statement
[Java] Make variables in extended for statement and for Each statement immutable
A quick explanation of the five types of static in Java
[Java] Beginner's understanding of Servlet-②
Java debug execution [for Java beginners]
[Java] Basic statement for beginners
[Java] Generics classes and generics methods
[Java] Beginner's understanding of Servlet-①
Java beginners briefly summarized the behavior of Array and ArrayList
[Ruby] Creating code using the concept of classes and instances
Comparison of Web App for Containers and Azure Container Instances
About classes and instances (evolution)
Consideration about classes and instances
[Java] Summary of for statements
Java for beginners, data hiding
StringUtils.isNotBlank is convenient for empty judgment and null judgment in java
Implementation of gzip in java
Tips for using Salesforce SOAP and Bulk API in Java