Java: Classes & Objects
In Java, a class is a blueprint or a template that defines the behavior and properties of objects. An object is an instance of a class, which is created using the new
keyword.
To define a class in Java, you use the class
keyword, followed by the name of the class, and then the body of the class enclosed in curly braces. For example:
public class MyClass {
// instance variables
private int x;
private String name;
// constructor
public MyClass(int x, String name) {
this.x = x;
this.name = name;
}
// methods
public int getX() {
return x;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In this example, MyClass
is a class with two instance variables (x
and name
), a constructor that takes two arguments to initialize these variables, and three methods (getX
, getName
, and setName
).
To create an object of this class, you use the new
keyword and call the constructor with the appropriate arguments. For example:
MyClass obj = new MyClass(42, "John");
This creates a new object of type MyClass
with x
initialized to 42 and name
initialized to “John”. You can then call the methods on this object, for example:
System.out.println(obj.getX()); // prints 42
System.out.println(obj.getName()); // prints "John"
obj.setName("Jane");
System.out.println(obj.getName()); // prints "Jane"
This is just a simple example, but in practice, classes and objects are used extensively in Java to create complex software systems.