In Java, this
is a keyword that refers to the current instance of a class. It can be used inside the methods or constructors of a class to refer to the current object on which the method is being called or the constructor is being invoked.
class InternalOperations {
int x;
int y;
public InternalOperations(int a, int b) {
this.x = a;
this.y = b;
}
}
public class Main {
public static void main(String[] args) {
InternalOperations someObj = new InternalOperations(10, 20);
System.out.println("X Value: " + someObj.x);
System.out.println("Y Value: " + someObj.y);
InternalOperations otherObj = new InternalOperations(5, 55);
System.out.println("X Value: " + otherObj.x);
System.out.println("Y Value: " + otherObj.y);
}
}
This Java program defines two classes: InternalOperations
and Main
.
The InternalOperations
class has two instance variables x
and y
of type int
. It also has a constructor that takes two integer parameters a
and b
, and initializes the instance variables x
and y
with the values of the parameters.
class InternalOperations {
int x;
int y;
public InternalOperations(int a, int b) {
this.x = a;
this.y = b;
}
}
The Main
class contains the main()
method, which is the entry point of the program.
Inside the main()
method, two objects of the InternalOperations
class are created using the new
keyword and the constructor that takes two integer arguments.
The first object is assigned to a reference variable named someObj
, and the second object is assigned to a reference variable named otherObj
.
public class Main {
public static void main(String[] args) {
InternalOperations someObj = new InternalOperations(10, 20);
InternalOperations otherObj = new InternalOperations(5, 55);
// ...
}
}
After the objects are created, the values of the instance variables x
and y
of both objects are printed using the System.out.println()
method.
System.out.println("X Value: " + someObj.x);
System.out.println("Y Value: " + someObj.y);
System.out.println("X Value: " + otherObj.x);
System.out.println("Y Value: " + otherObj.y);
The output of the program will be:
X Value: 10
Y Value: 20
X Value: 5
Y Value: 55
This shows that each object of the InternalOperations
class has its own instance variables x
and y
, which can be initialized and accessed independently of each other.
The program demonstrates the use of constructors to create objects of a class and the use of instance variables to store object-specific data.
No comments:
Post a Comment