Classes and Objects
In object-oriented programming (OOP), a class is a blueprint or template for creating objects. It defines the attributes (data fields) and behaviors (methods) that an object of that class will have.
For example, let's consider a Person
class. The Person
class may have attributes like name
and age
, and methods like getName()
and getAge()
.
1public class Person {
2 private String name;
3 private int age;
4
5 public Person(String name, int age) {
6 this.name = name;
7 this.age = age;
8 }
9
10 public String getName() {
11 return name;
12 }
13
14 public int getAge() {
15 return age;
16 }
17}
To create an object of the Person
class, we use the new
keyword followed by the class name and any required parameters for the constructor. The constructor initializes the object with the provided values.
1Person person = new Person("John", 25);
Once the object is created, we can access its attributes and methods using the object name followed by the dot operator. For example, to get the name of the person, we can use person.getName()
.
1String name = person.getName();
Classes and objects are fundamental concepts in OOP and provide a way to represent and interact with real-world entities in code. They enable code organization, reusability, and encapsulation of data and functionality.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// Create an instance of the Person class
Person person = new Person("John", 25);
// Access the attributes and methods of the Person object
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}