Ticker

6/recent/ticker-posts

Class and Object in Java OOPs

Class and Object in Java OOPs

1. Introduction:
Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects." Java, being an object-oriented language, enables developers to create classes and objects to model real-world entities and their behaviors. Classes serve as blueprints for objects, defining their structure and behavior, while objects are instances of these classes that represent tangible entities.

2. Creating a Class:
In Java, classes are created using the class keyword. Let's create a simple class called Car to demonstrate this:

java
public class Car {
// Fields or Data Members
String brand;
String model;
int year;

// Methods
void start() {
System.out.println("Car is starting...");
}

void accelerate() {
System.out.println("Car is accelerating...");
}

void brake() {
System.out.println("Car is braking...");
}
}

3. Instantiating Objects:
Once the class is defined, we can create objects based on that class using the new keyword. Each object will have its own set of data members and can invoke the methods defined in the class.

java
public class Main {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
Car car2 = new Car();

// Setting data for car1
car1.brand = "Toyota";
car1.model = "Corolla";
car1.year = 2020;

// Setting data for car2
car2.brand = "Honda";
car2.model = "Civic";
car2.year = 2019;

// Invoking methods
car1.start();
car1.accelerate();

car2.start();
car2.brake();
}
}

4. Explanation:

  • In the example above, we create a class Car with fields brand, model, and year, and three methods start(), accelerate(), and brake().
  • We then instantiate two objects car1 and car2 of type Car using the new keyword.
  • We set the data members for each car object individually.
  • Finally, we call the methods on each car object to perform specific actions.

5. Output:
The output of the above code will be:

csharp
Car is starting...
Car is accelerating...
Car is starting...
Car is braking...

This demonstrates the basic usage of classes and objects in Java. With OOP, you can create more complex systems by modeling real-world entities as classes and utilizing the power of objects to represent and interact with these entities in your code.

Post a Comment

0 Comments