Java is an object-oriented programming (OOP) language, which means it revolves around the concept of classes and objects. In this article, we will explore what classes and objects are and how to use them in Java with various examples.
Classes in Java
In Java, a class is a blueprint for creating objects. It defines the attributes (data members) and methods (functions) that an object of the class will have. Let's create a simple class called Person
to understand this concept better:
public class Person {
// Data members (attributes)
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display information
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
In the above example, we've defined a Person
class with two attributes: name
and age
. We also have a constructor to initialize these attributes and a method called displayInfo()
to display the person's information.
Objects in Java
Objects are instances of classes. They are created using the new
keyword. Let's create two Person
objects:
public class Main {
public static void main(String[] args) {
// Create two Person objects
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
// Call the displayInfo() method
person1.displayInfo();
person2.displayInfo();
}
}
Here, we've created two Person
objects, person1
and person2
, and called the displayInfo()
method to display their information.
Accessing Class Members
You can access class members (attributes and methods) using the dot (.) operator. For example:
// Accessing attributes
String personName = person1.name;
int personAge = person2.age;
// Calling methods
person1.displayInfo();
Classes and objects are fundamental concepts in Java and object-oriented programming. They allow you to model real-world entities and their behaviors in a structured way. By defining classes and creating objects, you can build complex and organized Java applications.
In this article, we've covered the basics of Java classes and objects, including how to define a class, create objects, and access their members. This is just the beginning of your journey into Java programming, as there are many more advanced topics to explore in the world of OOP.