Java classes and instances to understand in the figure

When you start learning Java programming, you'll have a rather early understanding of ** classes and instances **. I personally think that the hurdles for beginners are a little high. Often in reference books and online articles

A class is a design document and an instance is an entity created based on the design document.

I often see things like that, but I feel that only people with programming experience or sense can understand this. At the beginning of Java learning, I couldn't understand with such a conceptual explanation.

This article is for people who don't have much understanding of ** classes and instances **, just like I did when I started learning Java (this article uses Java 8). Please note that the figures are just images and cannot be expressed accurately.

instance

You can create an instance by newing from class. In Java, you basically create an instance and execute the process. The following is common, but I'm writing a program that instantiates from a human class.

class Human {

	String name;
	int age;

	Human(String name, int age) {
		this.name = name;
		this.age = age;
	}

	void greet() {
		System.out.printf("Nice to meet you,%s.\n", this.name);
	}
}

public static void main(String[] args) {

	Human humanA = new Human("Kaneda", 16);
	Human humanB = new Human("island", 15);

}

Create an instance with a name and age from the Human class that represents a human, the above creates two instances. I tried to figure this out.

WS000001.JPG

Create an instance from the class and deploy it in memory. Then, assign the reference value (address in memory) of that instance to the variable. Now let's execute the greeting method of the two instances generated above.

public static void main(String[] args) {

	Human humanA = new Human("Kaneda", 16);
	Human humanB = new Human("island", 15);

	humanA.greet(); //Nice to meet you, my name is Kaneda.
	humanB.greet(); //Nice to meet you, this is an island.
}

Since the name is different for each instance, the output will be different.

WS000002.JPG

Creating and operating each entity from a class is the basic operation of a program in Java.

static modifier

static literally means static. It gets a little confusing when it comes out, but be sure to understand it, as programming without understanding it can lead to ridiculous bugs. Variables and methods with static modifiers are also called class variables and class methods, respectively. Let's add each to the previous human class.

class Human {

	static final String classification = "mammalian"; // <-Class variables
	String name;
	int age;

	Human(String name, int age) {
		this.name = name;
		this.age = age;
	}

	static final boolean isMammal() { // <-Class method
		return true;
	}

	void greet() {
		System.out.printf("Nice to meet you,%s.\n", this.name);
	}
}

Added classification, which means classification as a static variable, and isMammal, which confirms mammals as a static method, to human classes. The final qualifier is a qualifier that makes it non-rewritable. Variables make it impossible to change values, and methods make it impossible to override. Now, let's access the added member.

public static void main(String[] args) {

	Human humanA = new Human("Kaneda", 16);
	Human humanB = new Human("island", 15);
	
	System.out.println(humanA.classification); //mammalian
	System.out.println(humanB.isMammal()); // true

}

Members with the static modifier belong to the class. So you are accessing the class via an instance. I also made a diagram of this.

WS000003.JPG

By the way, if you write the above code in eclipse, you will get a warning message that "... requires static access". This is because Java has an implicit rule that class members should access the class directly. It's difficult to tell whether it's a class property or an instance property via an instance. In this case, it is correct to access the class directly as follows.

System.out.println(Human.classification); //mammalian
System.out.println(Human.isMammal()); // true

That is, the static modifier must be given to instance-independent members. From an object-oriented perspective, the "mammal" classification of humans is a definition that does not differ between instances no matter what instance they create. I added final because the definition (that humans are "mammals") will not change in the future.

If you make a mistake in using it ...

I said that if you use static incorrectly, it will lead to bugs, but I will actually write the incorrect usage of static. Let's add a static growOld method that makes the above human class age. Think about what it means for humans to get older.

class Human {
	static final String classification = "mammalian";
	String name;
	int age;

	Human(String name, int age) {
		this.name = name;
		this.age = age;
	}

	static void growOld(){
		age++; // <-Compile error
	}

	/*Omission*/
}

I get a compile error saying "Unable to statically reference non-static field age" in the added growOld method.

WS000001.JPG

It's a non-static field, that is, an instance field, so it can't be accessed from class methods. When this happens, I realize that it is a mistake to define the aging growOld method as static, but sometimes it is not possible to remove static from the method due to the parent class or framework. In such a case, let's think that the design to access the field is strange in the first place. Very rarely, there are idiots who make variables (age age in this case) static, but ** don't make variables static **. It is not possible for all humans to age at the same time at the same time. When defining static members, think again from the design level.

In addition to variables and methods, there are inner classes that are members that can be given static. I won't cover inner classes in this article, but be aware that they have a slightly different meaning than variables and methods.

Inheritance

Java allows you to inherit from other classes and access members of the inherited class. The inherited class is also called the parent class or superclass of the inheriting class. Next, I would like to create an instance from a class that inherits another class. The following newly defines a Japanese class and an American class that inherit the above human class, and executes the greeting method from each instance.

class Japanese extends Human {
	
	Japanese(String name, int age) {
		super(name, age);
	}
	
	@Override
	void greet() {
		super.greet();
		System.out.println("I am Japanese.");
	}
	
}

class American extends Human {

	American(String name, int age) {
		super(name, age);
	}
	
	@Override
	void greet() {
		super.greet();
		System.out.println("I am American.");
	}
	
}

public static void main(String[] args) {

	Japanese japanese = new Japanese("Kumi", 15);
	American american = new American("Emily", 15);
	
	japanese.greet();
	//Nice to meet you, this is Kumi.
	//I am Japanese.
	
	american.greet();
	//Nice to meet you, my name is Emily.
	//I am American.

}

The child class inherits the members of the parent class as they are. In other words, the child instance can use the members of the parent class as they are. Therefore, it is possible to access the parent greeting method in the child greeting method. WS000000.JPG

override

By the way, both Japanese and Americans inherit humans, so instances can behave as humans. The following is a list of human beings, and they are greeted in order.

List<Human> humans = new ArrayList<>();
humans.add(new Japanese("Kumi", 15));
humans.add(new Japanese("Ken", 15));
humans.add(new American("Emily", 15));
humans.add(new American("Billy", 15));
humans.forEach(h -> h.greet());
//Nice to meet you, this is Kumi.
//I am Japanese.
//Nice to meet you, my name is Ken.
//I am Japanese.
//Nice to meet you, my name is Emily.
//I am American.
//Nice to meet you, my name is Billy.
//I am American.

What I would like to pay attention to here is the content of the greeting. I am greeting as a human being, but Japanese and Americans are greeting each child class. Overriding a method of a parent class with a method of a child class in this way is called overriding.

WS000000.JPG

By the way, in the following cases, "Yamato-damashii" is a Japanese member and cannot be accessed with humanoid variables. Even if it is a Japanese instance, Japanese members cannot use it unless they behave as Japanese.

class Japanese extends Human {
	
	String japaneseSoul = "Yamato soul"; // <-Japanese soul
	
	Japanese(String name, int age) {
		super(name, age);
	}
	
	@Override
	void greet() {
		super.greet();
		System.out.println("I am Japanese.");
	}
	
}

Japanese japanese = new Japanese("Kumi", 15);
Human human = new Japanese("Ken", 15);
	
System.out.println(japanese.japaneseSoul); //Yamato soul
System.out.println(human.japaneseSoul); // <-Compile error

(I'm sorry I can't think of a good example of what Japanese people have.)

Finally

Java is often used as an introductory language for programming and is the language used by many systems. But if you don't understand the relationship between classes and instances, you can't do correct Java programming, and you can't understand object-oriented programming. I hope this will lead to the understanding of those who are in trouble.

Recommended Posts

Java classes and instances to understand in the figure
java (classes and instances)
About the difference between classes and instances in Ruby
[java8] To understand the Stream API
How to use classes in Java?
Classes and instances Java for beginners
[For beginners] Explanation of classes, instances, and statics in Java
Classes and instances
[Java] Various summaries attached to the heads of classes and members
Java programming (classes and instances, main methods)
How to get the date in java
Java to C and C to Java in Android Studio
Specify the order in which configuration files and classes are loaded in Java
The story of forgetting to close a file in Java and failing
Understand the difference between int and Integer and BigInteger in java and float and double
How to create your own annotation in Java and get the value
[Java] Understand the difference between List and Set
Regarding the transient modifier and serialization in Java
About the idea of anonymous classes in Java
Differences in writing Java, C # and Javascript classes
[Java] Understand in 10 minutes! Associative array and HashMap
[Ruby] Classes and instances
About classes and instances
Ruby classes and instances
[Java] How to omit the private constructor in Lombok
Write ABNF in Java and pass the email address
Source used to get the redirect source URL in Java
How to convert A to a and a to A using AND and OR in Java
I tried to implement the Euclidean algorithm in Java
Gzip-compress byte array in Java and output to file
[Java] How to get the key and value stored in Map by iterative processing
About classes and instances (evolution)
Consideration about classes and instances
About abstract classes in java
Java thread to understand loosely
About Ruby classes and instances
Creating Ruby classes and instances
Java abstract methods and classes
Input to the Java console
How to get the class name / method name running in Java
I didn't understand the behavior of Java Scanner and .nextLine ().
JSON in Java and Jackson Part 1 Return JSON from the server
Understand the rough flow from request to response in SpringWebMVC
How to separate words in names in classes, methods, and variables
[Java] Change language and locale to English in JVM options
I tried to summarize the basics of kotlin and java
Difference between Java and JavaScript (how to find the average)
Refer to C ++ in the Android Studio module (Java / kotlin)
Command to check the number and status of Java threads
[Android, Java] Convenient method to calculate the difference in days
Understand the Singleton pattern by comparing Java and JavaScript code
[Ruby] Creating code using the concept of classes and instances
What happened in "Java 8 to Java 11" and how to build an environment
Create a method to return the tax rate in Java
How to call and use API in Java (Spring Boot)
Correct the character code in Java and read from the URL
Reasons to use Servlet and JSP separately in Java development
Make your own simple server in Java and understand HTTP
Contributed to Gradle and was named in the release notes
Think about the differences between functions and methods (in Java)
How to develop and register a Sota app in Java