Object Oriented Programming Java Tutorial

Advertisement

Object-oriented programming Java tutorial offers a structured approach to programming that is based on the concept of "objects." These objects can represent real-world entities, encapsulating both data and behavior. Java, being a fully object-oriented language, provides a robust framework for developing applications using this paradigm. In this tutorial, we will explore the core concepts of object-oriented programming (OOP) in Java, delve into its principles, and provide practical examples to help you understand how to implement OOP effectively.

Understanding Object-Oriented Programming



Object-oriented programming is a programming paradigm that relies on the concept of objects. Objects are instances of classes, which are blueprints for creating objects. OOP is centered around four main principles: encapsulation, inheritance, polymorphism, and abstraction. These principles enable developers to create modular, reusable, and maintainable code.

1. Principles of Object-Oriented Programming



To grasp the power of OOP, it’s essential to understand its four fundamental principles:

- Encapsulation: This principle refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit known as a class. Encapsulation restricts direct access to some of an object's components, which can prevent the accidental modification of data. It is often implemented using access modifiers.

- Inheritance: Inheritance allows one class (the child class) to inherit the attributes and methods of another class (the parent class). This promotes code reusability and establishes a hierarchical relationship between classes. For example, a class `Animal` can have subclasses like `Dog` and `Cat`.

- Polymorphism: Polymorphism means "many forms." In Java, it allows objects to be treated as instances of their parent class. The two types of polymorphism are compile-time (method overloading) and runtime (method overriding). This enables a single interface to control access to a general class of actions.

- Abstraction: Abstraction is the process of hiding the complex implementation details and showing only the essential features of the object. In Java, abstraction is achieved using abstract classes and interfaces.

Setting Up Your Java Environment



Before diving into OOP concepts, you need to set up your Java development environment. Here’s how to do that:

1. Download and Install Java Development Kit (JDK):
- Visit the official Oracle website or OpenJDK.
- Download the latest version of JDK suitable for your operating system.
- Follow the installation instructions.

2. Set Up an Integrated Development Environment (IDE):
- Popular IDEs for Java include Eclipse, IntelliJ IDEA, and NetBeans.
- Download and install your chosen IDE.
- Configure the IDE to recognize the JDK.

3. Create Your First Java Project:
- Open your IDE and create a new Java project.
- Set up your project structure and create your first Java class.

Creating Classes and Objects



Now that your environment is set up, let’s start with the basic building blocks of OOP: classes and objects.

1. Defining a Class



A class is defined using the `class` keyword. Below is a simple example of a class definition:

```java
public class Car {
// Attributes
String color;
String model;
int year;

// Method
void displayDetails() {
System.out.println("Car Model: " + model + ", Color: " + color + ", Year: " + year);
}
}
```

In the example above, we defined a class named `Car` with three attributes: `color`, `model`, and `year`. We also created a method `displayDetails()` to print the car's details.

2. Creating Objects



An object is an instance of a class. You can create an object of the `Car` class as follows:

```java
public class Main {
public static void main(String[] args) {
// Creating an object of Car
Car myCar = new Car();
myCar.color = "Red";
myCar.model = "Toyota";
myCar.year = 2020;

// Calling the method
myCar.displayDetails();
}
}
```

In this example, we created an object named `myCar` and assigned values to its attributes. Then, we called the `displayDetails()` method to print the car's information.

Encapsulation in Java



Encapsulation is a key concept in OOP, and it can be implemented in Java using access modifiers. The most common access modifiers are `private`, `public`, and `protected`.

1. Implementing Encapsulation



Here’s how you can implement encapsulation in Java:

```java
public class Student {
// Private attributes
private String name;
private int age;

// Public getter and setter methods
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
```

In this example, the attributes `name` and `age` are declared as `private`. This means they cannot be accessed directly from outside the class. Instead, public getter and setter methods are provided to access and modify the values.

Inheritance in Java



Inheritance allows classes to inherit properties and methods from other classes, promoting code reusability.

1. Implementing Inheritance



Here’s an example of inheritance in Java:

```java
// Parent class
public class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Child class
public class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
```

In this example, the `Dog` class inherits from the `Animal` class. This means the `Dog` class can access the `eat()` method from the `Animal` class.

2. Using Inheritance



To use these classes, you can create a `main` method:

```java
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Dog's own method
}
}
```

When you run this code, it will display:

```
This animal eats food.
The dog barks.
```

Polymorphism in Java



Polymorphism allows methods to do different things based on the object that it is acting upon.

1. Method Overloading



Method overloading is a form of compile-time polymorphism. It allows multiple methods in the same class to have the same name but different parameters.

```java
public class MathOperations {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {
return a + b;
}
}
```

In this example, the `add` method is overloaded with two different parameter types.

2. Method Overriding



Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass.

```java
// Parent class
public class Vehicle {
void start() {
System.out.println("Vehicle is starting.");
}
}

// Child class
public class Bike extends Vehicle {
@Override
void start() {
System.out.println("Bike is starting.");
}
}
```

In this case, the `Bike` class overrides the `start` method of the `Vehicle` class.

3. Using Polymorphism



You can create a method that accepts a reference of the parent class:

```java
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Bike();
myVehicle.start(); // Calls the overridden method
}
}
```

This will output:

```
Bike is starting.
```

Abstraction in Java



Abstraction allows you to define abstract classes and interfaces that represent a contract for other classes.

1. Abstract Classes



An abstract class cannot be instantiated and can contain abstract methods (without a body) and concrete methods (with a body).

```java
abstract class Shape {
abstract void draw(); // Abstract method

void display() {
System.out.println("Displaying shape.");
}
}

class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle.");
}
}
```

2. Interfaces



An interface is a reference type in Java, similar to a class that can contain only constants, method signatures, default methods, static methods, and nested types.

```java
interface Animal {
void sound(); // Abstract method
}

class Cat implements Animal {
@Override
public void sound() {
System.out.println("Meow");
}
}
```

3. Using Abstraction



You can use the classes and interfaces created above as follows:

```java
public class Main {
public static void main(String[] args) {
Shape myShape = new Circle();
myShape

Frequently Asked Questions


What is Object-Oriented Programming (OOP) in Java?

Object-Oriented Programming (OOP) in Java is a programming paradigm that uses 'objects' to design applications. It is based on several key principles including encapsulation, inheritance, polymorphism, and abstraction.

What are the four main principles of OOP in Java?

The four main principles of OOP in Java are: Encapsulation (bundling data and methods), Inheritance (creating new classes based on existing ones), Polymorphism (using a single interface to represent different underlying forms), and Abstraction (hiding complex reality while exposing only the necessary parts).

How do you create a class in Java?

In Java, a class is created using the 'class' keyword followed by the class name and a pair of curly braces. For example: `class MyClass { // class body }`.

What is encapsulation and how is it implemented in Java?

Encapsulation is the principle of restricting access to certain details of an object. In Java, it is implemented using access modifiers like private, protected, and public to control visibility and access to class members.

What is the difference between inheritance and polymorphism in Java?

Inheritance allows a new class to inherit properties and methods from an existing class, promoting code reuse. Polymorphism allows methods to be defined in multiple forms, enabling a single interface to represent different underlying forms.

Can you explain how constructors work in Java?

Constructors in Java are special methods that are called when an object is instantiated. They have the same name as the class and do not have a return type. Constructors can be overloaded to create objects in different ways.

What is an interface in Java and how does it differ from an abstract class?

An interface in Java is a reference type that can contain only constants, method signatures, default methods, static methods, and nested types. It cannot contain instance fields or constructors. Unlike an abstract class, a class can implement multiple interfaces, allowing for a form of multiple inheritance.

How do you achieve abstraction in Java?

Abstraction in Java is achieved through abstract classes and interfaces. An abstract class can have both abstract methods (without implementation) and concrete methods (with implementation). Interfaces provide a way to define methods without implementing them, allowing classes to implement the methods in their own way.