This article is a memorandum. Although it is a reference book level content, the code posted in this article is about ~~ ** The mistaken ** is the center. This is for the purpose of posting the part that was actually mistaken during coding and posting it for self-reflection. ~~ In addition, I will review the Java Silver exam questions at a later date, so I will not touch on the deep part here.
Language: Java11, JDK13.0.2 Operating environment: Windows 10
I remember talking about objects and instances confusingly before, but I would like to touch on them again.
First, prepare the Cat
class as usual.
Cat.java
class Cat
{
public static int sumCats = 0;
private int age;
private double weight;
public Cat()
{
age = 0;
weight = 0.0;
sumCats++;
System.out.println("A new cat has arrived!");
}
public void setCat(int a,double w)
{
age = a;
weight = w;
System.out.println("This cat is age" + age + "Age, weight" + weight + "It is kg.");
}
public static void showSumCats()
{
System.out.println("Now in total" + sumCats + "I have a cat.");
}
}
Consider the case where two cats are prepared using this Cat
class.
-** 2 cats ** are separate ** objects ** from the same Cat
class.
-Two cats have their own ʻage, weight` fields.
In the above, the two cats use the ** instance variable **, which is the field associated with each object, and the ** instance method **, which is the method associated with the object. Have.
These instance variables and methods "become accessible after the object is created ( new
) ".
Misunderstandings I had so far ・ Object ≒ instance
⇒Field method for each object = Instance variable method * new !! *
However, there are some members (field methods) that you want to handle before the object is created. Therefore, members that are ** associated with the class itself ** can be declared as static
and used.
public static void showSumCats ()
is
Refer to the ** class variable sumCats
** declared aspublic static int sumCats = 0;
, and ** constructor Cat () ** is called every time new
is done, and it is automatically incremented. It has become. This links "how many times Cat objects were created" with "total number of cats".
Since showSumCats ()
is static
, it is a method that can be called even if" the Cat object has never been created ". Therefore, "0 cats" can be indicated.
** Only within instance methods **, this.age
and this.weight
can be written to indicate only the field values associated with the object.
The story of local variables is omitted.
If you don't understand well whether the variables / methods you are going to handle in the main function are class-related or object-related by static
, there are quite a lot of problems to be struck here.
I write variables and expressions as much as possible and compile them, so if I want to quote them completely, I will describe that.
Easy Java 7th Edition Java SE11 Silver Problem Collection (commonly known as Kuromoto)
Recommended Posts