Java is an object-oriented programming language. Everything in Java is related to classes and objects along with attributes and methods. For example, destroyers have attributes such as firepower and anti-submarine value, and have methods such as anti-submarine attack.
Use the keyword class
when creating a class.
Battleship.java
public class Battleship {
int x = 3;
}
The class name must start with a capital letter and the class name and file name must match. In this case, ** Battleship ** in ** Battleship **. Java and ** Battleship ** in the class name match.
In Java, you create an object from a class. When creating an object, write the class name after new.
Battleship.java
public class Battleship {
int x = 3;
public static void main(String[] args) {
Battleship yamato = new Battleship(); //Create an object called yamato in the Battleship class
System.out.println(yamato.x); //Output the value of x
}
}
You can also create multiple objects in one class.
Battleship.java
public class Battleship {
int x = 3;
public static void main(String[] args) {
Battleship yamato = new Battleship(); //Create an object called yamato in the Battleship class
Battleship musashi = new Battleship(); //Create an object called musashi in the Battleship class
System.out.println(yamato.x); //Output the value of x
System.out.println(musashi.x); //Output the value of x
}
}
Recommended Posts