JAVA and OOPs Concepts

Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods)

Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as model and color, and methods, such as drive and brake.

A Class is like an object constructor, or a “blueprint” for creating objects.

What is a Class?

A class is a blueprint or prototype that defines the variables and the methods (functions) common to all objects of a certain kind.

Create a Java Class

To create a class, use the keyword class:

Create a class named “Car” with a variable model and colour:

public class Car{
  string model;
  string colour;
}

What is an Object?

An object is a representative or specimen of a class. Software objects are often used to model real-world objects you find in everyday life.

Create a JAVA Object

In Java, an object is created from a class. We have already created the class named Car, so now we can use this to create objects.

To create an object of Car, specify the class name, followed by the object name, and use the keyword new:

Car myCar = new Car();

Examples of class and objects

ClassObjects
Fruit Apple
Banana
Mango
Car Volvo
Audi
Toyota
Examples – Class and Objects


Features of OOPs :

Abstraction 

Abstraction is the process of exposing the relevant things and hiding the irrelevant details. The easiest way to understand and appreciate this concept of handling complexity is by studying the example of Globe, a model/prototype of earth that is used by students to understand its geography. Globe provides only that information that is required and if too much of information is mentioned in it i.e. streets, lakes etc, it becomes too complex to comprehend. Hence Globe abstracts unwanted information and makes it easy to comprehend the complex earth.

JAVA Abstract Classes and Methods

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and methods:

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods:

abstract class Animal {
  public abstract void animalSound();
  public void sleep() {
    System.out.println("Zzz");
  }
}
 
 

From the example above, it is not possible to create an object of the Animal class:

Animal myObj = new Animal(); // will generate an error

To access the abstract class, it must be inherited from another class. Let’s convert the Animal class we used in the Polymorphism chapter to an abstract class:

Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.

Example

// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzz");
  }
}

// Subclass (inherit from Animal)
class Pig extends Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

Encapsulation 

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The data is not accessible to the outside world and only those functions that are wrapped in the class can access it. These functions provide the interface between the object’s data and the program. The insulation of the data from the direct access by the program is called data hiding.
In OOP, code and data are merged into an object so that the user of an object can never peek inside the box. This is defined as encapsulation (Object is a capsule encapsulating data and behavior). All communication to it is through messages (function calls which we use to communicate to the object). Messages define the interface to the object. Everything an object can do is represented by its message interface. Therefore, we need not know anything about what is in the object when we use it.

JAVA Encapsulation

The meaning of Encapsulation, is to make sure that “sensitive” data is hidden from users. To achieve this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

Get and Set

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

Example

public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

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

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside this class:

Example

public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.name = "John";  // error
    System.out.println(myObj.name); // error 
  }
}

Inheritance 

Inheritance is the process by which one class acquires the properties and functionalities of another class. This is important because it supports the concept of hierarchical classification.. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it.

Java Inheritance (Subclass and Superclass)

In Java, it is possible to inherit attributes and methods from one class to another. We group the “inheritance concept” into two categories:

  • subclass (child) – the class that inherits from another class
  • superclass (parent) – the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

Example

class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
  public void honk() {                    // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}
 

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier. If it was set to private, the Car class would not be able to access it.

Why And When To Use “Inheritance”?

– It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to perform different tasks.


The final Keyword

If you don’t want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {
  ...
}

class Car extends Vehicle {
  ...
}

The output will be something like this:Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
                  ^
1 error)

Polymorphism 

Polymorphism is a feature that allows one interface to be used for a general class of actions. An operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. It plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance.
Ex:
add(int a, int b)
add(int a, float b, int c)
add(int a, int b, float c, double d)
Here different datatypes are being added using the same interface.

Java Polymorphism

Polymorphism means “many forms”, and it occurs when we have many classes that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds – And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

Example

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.

Now we can create Pig and Dog objects and call the animalSound() method on both of them:

Example

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}