Java Object and Class Page
Syntax
class ClassName {
type instanceVariableName;
type instanceVariableName;
className() {
// constructor
}
void methodName() {
// method body
}
}
Example
class Person {
String name;
int age;
Person() {
name = "John";
age = 30;
}
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
class Main {
public static void main(String[] args) {
Person person = new Person();
person.displayInfo();
}
}
Output
Name: John
Age: 30
Explanation
In Java, an object is an instance of a class. A class is a blueprint that defines the properties and behavior of objects.
The example above defines a class called Person
. This class has two instance variables, name
and age
, and a constructor that initializes these variables with default values. It also defines a method called displayInfo
that displays the values of the instance variables.
In the Main
class, an instance of the Person
class is created using the new
keyword and the constructor is called. The displayInfo
method is then called on this instance, which displays the name and age of the person.
Use
Java objects and classes are used to model real-world entities and concepts in software. They allow you to encapsulate data and behavior into reusable components, making your code more modular and easier to maintain.
Objects can also be used to represent complex data structures or to perform specific tasks. For example, you could create an object to represent a bank account, or an object to perform a specific mathematical operation.
Important Points
- A class is a blueprint for creating objects.
- An object is an instance of a class.
- A class can have instance variables and methods.
- The
new
keyword is used to create an instance of a class. - The constructor is called when an object is created to initialize its instance variables.
Summary
In Java, an object is an instance of a class. A class is a blueprint that defines the properties and behavior of objects. Classes can have instance variables and methods. Objects are created using the new
keyword and the constructor is called to initialize the variables. Java objects and classes are used to model real-world entities and concepts in software and to make your code more modular and easier to maintain.