To initialize a new class in Java, you need to create an instance of the class using the new
operator and a constructor.
Here is an example of how to initialize a new class in Java:
public class MyClass { // Properties private int a; private String b; // Constructor public MyClass(int a, String b) { this.a = a; this.b = b; } // Getters and setters public int getA() { return a; } public void setA(int a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } } public class Main { public static void main(String[] args) { // Initialize a new MyClass object MyClass obj = new MyClass(1, "Hello"); // Print the values of the object's properties System.out.println(obj.getA()); System.out.println(obj.getB()); } }
In this example, the MyClass
class has two properties, a
and b
, and a constructor that takes two arguments and initializes the object's properties with the given values. The Main
class creates a new MyClass
object using the new
operator and the constructor, and then prints the values of the object's properties using the getters.
Output:
1 Hello
For more information on classes and constructors in Java, you can refer to the Java documentation.