Mark As Completed Discussion

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().

TEXT/X-JAVA
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.

TEXT/X-JAVA
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().

TEXT/X-JAVA
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.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment