You are on page 1of 1

Write code to create an object in Java.

[5 marks]
 1 Comment
example of Java code that creates an object of a class:

public class MyClass {


private int myInt;
private String myString;

public MyClass(int myInt, String myString) {


this.myInt = myInt;
this.myString = myString;
}

public int getMyInt() {


return myInt;
}

public String getMyString() {


return myString;
}

public static void main(String[] args) {


// Creating an object of MyClass
MyClass myObject = new MyClass(10, "Hello, World!");

// Accessing object properties


int intValue = myObject.getMyInt();
String stringValue = myObject.getMyString();

// Printing object properties


System.out.println("MyInt: " + intValue);
System.out.println("MyString: " + stringValue);
}
}
In this example, we have a class named MyClass with two private instance variables (myInt and
myString). The class has a constructor that takes values for these variables and initializes them.
The class also has getter methods to access the values of these variables.
In the main method, we create an object myObject of type MyClass using the new keyword and
passing the constructor arguments. We then use the getter methods to access the values of myInt
and myString and print them to the console

You might also like