Java Class | OOP’s In Java

Java Class | OOP’s in Java

Class in java in detail with example

In Java, a class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that objects of the class will have. Here’s a detailed explanation with an example:

OOps in java

Class Declaration:

A class in Java is declared using the class keyword, followed by the class name. Here’s a simple example of a Person class:

public class Person {
// Fields (attributes)
String name;
int age;

// Constructor
public Person(String name, int age) {
    this.name = name;
    this.age = age;
}

// Method
public void sayHello() {
    System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}

}

Object Creation:

Once a class is defined, you can create objects (instances) of that class using the new keyword.
For example:

Person person1 = new Person(“Alice”, 30);
Person person2 = new Person(“Bob”, 25);

Fields and Methods:

Fields:

These are variables declared within a class. In the Person class, name and age are fields.

Methods:

These are functions defined within a class. The sayHello() method in the Person class is an example.

Constructors:

A constructor is a special method used for initializing objects. It has the same name as the class and no return type.
In the Person class, the constructor public Person(String name, int age) initializes the name and age fields of a Person object.

Access Modifiers:

The public keyword in Java is an access modifier that specifies the visibility of a class, method, or field.
public means the class, method, or field can be accessed by any other class.
Example Usage:

public class Main {
public static void main(String[] args) {
Person person1 = new Person(“Alice”, 30);
Person person2 = new Person(“Bob”, 25);

    person1.sayHello();
    person2.sayHello();
}

}

Output:

Hello, my name is Alice and I am 30 years old.
Hello, my name is Bob and I am 25 years old.
In this example, two Person objects are created and their sayHello() methods are called to print a greeting message.

1 thought on “Java Class | OOP’s In Java”

  1. Pingback: Object in Java | OOP's Concept - Fast News4U

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top