Class, Object & Object Orientation

A Class is a template or a blueprint from which Real Objects are created. A Class can contain:

Data member

Method

Constructor

Block

Class and Interface

What is a constructor and why do we need them?

A constructor is a special type of method whose name is the same as class name and without any return type. This is because the implicit return type of a class’ constructor is the class type itself.

A constructor initializes objects. It means, it initializes all global instance variables when an object is created.

It gives an advantage over initializing all the variables in a class each time an object is created. It would be simpler to have all the setup done at the time the object is first created. Because the requirement for initialization is so common, Java allows objects to initialize themselves when they are created. This automatic initialization is performed using a constructor.

A Java constructor cannot be abstract, static, final, and synchronized.

Example

// Create a ConstructorDemo class

public class ConstructorDemo {

  int x;  // Create an instance variable

  // Create a class constructor for the Main class

  public Main() {

    x = 5;  // Set the initial value for the class attribute x

  }

  public static void main(String[] args) {

    ConstructorDemo myObj = new ConstructorDemo ();

// Create an object of class ConstructorDemo (This will call the constructor)

    System.out.println(myObj.x); // Print the value of x

  }

}

Output

 5

One very important point to remember is, even if user does not declare any constructor in a class, JAVA provides a default constructor to the class. However, then you are not able to set initial values for object attributes.

In the above example, if we remove the below code, the output will be 0.

public Main() {

    x = 5;  // Set the initial value for the class attribute x

  }

It is because JAVA provides a default constructor to the ConstructorDemo class and the default value of x will be printed (default value of integer is 0).

Can we overload constructors?

Yes. Based on the argument(s) passed while creating an Object, the specific constructor will be used.

Example –

 public class OverloadDemo {

     public OverloadDemo(String str) {

                        // It will call the constructor with String

                        System.out.println("Parametrized constructor with single param");

            }

     public OverloadDemo(String str, int num) {

                        // It will call the constructor with String and integer argument

                        System.out.println("Parametrized constructor with double args");

            }

     public OverloadDemo(int num1, int num2, int num3) {

                        // It will call the constructor with 3 integer arguments

                        System.out.println("Parametrized constructor with three args");

            }

    public static void main(String args[]) {

                        // Creating an object using Constructor with 3 int arguments

                        OverloadDemo obj = new OverloadDemo(5, 5, 15);

            }

}

Output

Parametrized constructor with three args

Explanation

OverloadDemo class has 3 constructors defined. But when an actual object is created, it depends on how many arguments are passed, to determine which constructor will be used.

Can there be a private constructor?

Yes, we can have. The reason we need it is to prevent the instantiation of that class (which has a private constructor) outside of the class.

Normally we use private constructors in the following cases:

Singleton class

Static method only class

Final member only class

What are the different object-oriented features of JAVA? Explain with real life examples.

There are 4 main features of OO that JAVA uses. They are:

  • Inheritance
  • Encapsulation
  • Abstraction
  • Polymorphism

            Let us take an example of Mobile.

Class - A Class is a plan which describes the object. A class consists of state (variables) and behaviors (methods). Using the example of mobile, a mobile class can be designed using IMEI Number, Software, Storage as states and makeCall(), receiveMessage(), clickPhoto() as behaviors.

Object – Mobile companies create new phones every day, they can be treated as Objects.

           Mobile mbl1 = new Mobile ();

new Mobile() is the actual object while mbl1 is a reference variable pointing to the actual   object. It is very important to recognize the difference.

Inheritance – Inheritance is the ability to extend the functionality and information from a base class to a new class. This will help us to reuse the functionality which is defined before.

Let us think about the generic makeCall() method in a Samsung mobile which is inherited in a Samsung S5.

Encapsulation – Encapsulation is defined as the process of protecting information details from the outside world. It says how much access of a data field should be provided to the world so that it is not misused.

Talking about Bluetooth, we usually have it on our mobile. When we switch on the Bluetooth, I can connect to another mobile but not be able to access the other mobile features like dialing a number, accessing inbox etc. So, it means, another mobile’s inbox, contact list is encapsulated from the outside world.

Abstraction – Abstraction defines the process of extracting the relevant details to the outside world. The relevance, though, varies based on the member who is accessing the details.

In the above example, a user of the mobile only sees the dialing screen while calling another person. He does not care about the signal details his SIM card generates. But if calling functionality is not working, then, signal details are important for the mechanic who is fixing the issue.

Polymorphism - Polymorphism can be defined as the ability of doing the same operation but with different types of input.

Let’s say Samsung mobile has the 5MP camera available i.e. – it is having a functionality of cameraClick(). Now the same mobile is having Panorama mode available in camera, so functionality would be the same but with mode. This type is said to be Static polymorphism or Compile time polymorphism. See the example below where CameraClick() method is overloaded:

public void CameraClick()

{

System.out.println("Camera clicked");

}

public void CameraClick(string CameraMode)

{

System.out.println ("Camera clicked in " + CameraMode + " Mode");

}

Another type of Polymorphism is Runtime Polymorphism.

In the example below, there are 2 display() methods in 2 different classes. Which display()    method will be executed is decided by the actual object which is created at runtime.

Since we created an object of NokiaLumia class, the display() method associated with this class is executed.

class Nokia{

void display(){System.out.println("Default Display");}

}

class NokiaLumia extends Nokia{

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

public static void main(String args[]){

NokiaLumia NL = new NokiaLumia ();

NL.display();

}

Output

Theme display

Inheritance

In this section we will discuss Inheritance in detail with examples.

What is Inheritance? Explain with an example. 

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.

Example –

class Calculation {

   int z;

           

   public void addition(int x, int y) {

      z = x + y;

      System.out.println("The sum of the given numbers:"+z);

   }

           

   public void subtraction(int x, int y) {

      z = x - y;

      System.out.println("The difference between the given numbers:"+z);

   }

}

public class My_Calculation extends Calculation {

   public void multiplication(int x, int y) {

      z = x * y;

      System.out.println("The product of the given numbers:"+z);

   }

           

   public static void main(String args[]) {

      int a = 20, b = 10;

      My_Calculation demo = new My_Calculation();

      demo.addition(a, b);

      demo.subtraction(a, b);

      demo.multiplication(a, b);

   }

}

Output

The sum of the given numbers:30

The difference between the given numbers:10

The product of the given numbers:200

Explanation

In the given program, when an object to My_Calculation class is created, a copy of the contents of the superclass is made within it. That is why, using the object of the subclass you can access the members of a superclass.

Some specific points to remember with respect to Inheritance.                                                           
  • Java does not support multiple Inheritances; it provides Interface to solve this issue.
  • Through inheritance, a subclass cannot access private members of a super class.
  • In the subclass, super class state and behavior can be used using super() keyword.
  • Inheritance is useful for Code Reuse and Polymorphism.    
  • Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.                                                                                       
What is multilevel inheritance?

Multilevel inheritance allows a child class to inherit properties from a class that can inherit properties from some other classes. For example, class C can inherit its property from B class which itself inherits from A class.

What is multiple inheritance? 

When a class inherits from more than one class, that is called multiple inheritance.

Multiple inheritance is not allowed in java. Let us use the picture below to explain the reason.

Let’s assume class A has a method called display(). Class B & C inherits A and overrides display() method respectively. Now, when class D inherits B & C (which is not allowed in JAVA, but let’s assume for a moment that it is possible) and does not override display() method, then the JAVA compiler would not know which version of display() method should be used, from B or from C.

To avoid this ambiguity, multiple inheritance (also known as Deadly Diamond of Death; as the above picture looks like a Diamond) is not allowed in JAVA.  To overcome this problem, JAVA offers Interface.

What is IS A & HAS A relationship?

IS A relationship is easy to understand. It is the relational criteria to follow when a sub class is extending a superclass. For example, if class B extends A, then we say Class B IS A Class A.

But HAS A relationship is a little tricky. It’s also called composition.

When we say class A HAS A Class B; it means class A has a reference to an instance of class B.

Example -

class TestFlow {

int sqare(int n)

{

return n*n;

}

}

public class Glow {

double area (int rad)

{

double pi=3.14;

double rsqaure=(new TestFlow()).sqare(rad);

return pi*rsqaure;

}

public static void main(String[] args) {

System.out.println((new Glow()).area(5));

}

Explanation

As the arrow mark shows, Glow class has an instance reference of TestFlow class inside it and when required, we can delegate to TestFlow class for square() method. This reduces clumsiness inside Glow class. We can say, Glow HAS A TestFlow.

Encapsulation

What is encapsulation? 

Encapsulation is a mechanism of wrapping code and data together into a single unit.

We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.

Example

//File: Member.java

public class Member{

 //private data member

 private String name;

 //getter method for name

 public String getName(){

   return name;

 }

//setter method for name

public void setName(String name){

  this.name=name

 }

}

//File: Test.java

class Test{

public static void main(String[] args){

//creating instance of the encapsulated class

Member m=new Member ();

//setting value in the name member

m.setName("Tom");

//getting value of the name member

System.out.println(m.getName());

}

}

Explanation

In member.java class, we are setting the name of the member using a public setName() method and returning the name using a public getName() method. In Test.java class, we are passing the actual name in runtime and printing the same.

It is something to notice that the name instance variable in Member.java is a private element, and cannot be modified without using the setName() method, which is public.

How to create a Read Only & Write Only class using encapsulation?

Using encapsulation features, we can make a class read-only or write-only. A read only class means, none of the members of the class can be modified. A write only class means a class for which data members can be modified but cannot be read outside of the class.

Example – Read Only

//A Java class which has only getter methods.

public class Student{

//private data member

private String college="AKG";

//getter method for college

public String getCollege(){

return college;

}

}

Now nobody outside Student class can modify the college data member which is "AKG".

Example – Write Only

//A Java class which has only setter methods.

public class Student{

//private data member

private String college;

//getter method for college

public void setCollege(String college){

this.college=college;

}

}

Now, you can't get the value of the college, you can only change the value of the college data member.

Abstraction

What is abstraction in JAVA?

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.

Can we create an instance of Abstract Class?

No, we cannot create instances of Abstract Class. However, we can extend the abstract class to override the abstract methods of the Abstract Class and then create the instance of the child 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 Horse extends Animal {

  public void animalSound() {

    // The body of animalSound() is provided here

    System.out.println("The horse says: neigh neigh");

  }

}

class Main {

  public static void main(String[] args) {

    Horse horse = new Horse (); // Create a Horse object

    horse.animalSound();

    horse.sleep();

  }

}

Output

The horse says: neigh neigh

Zzz

What is the difference between Abstract Class & Interface?

The difference between Abstract Class & Interface is, an Abstract Class can be fully or partially abstract. It means, Abstract class can have all methods which are abstract as well as few abstract and few concrete methods. But an Interface always have all abstract methods, it can not hold concrete methods.

Why do we need an interface if we have an abstract class?

Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Also, if we want the behaviors from multiple areas, we need Interface.

Example

            Let’s see the below 2 examples to find when to use Abstract Class & Interface.

abstract class Car {

public void accelerate() {

System.out.println("Do something to accelerate");

}

public void applyBrakes() {

System.out.println("Do something to apply brakes");

}

public abstract void changeGears();

}

Now, real cars (Alto, for example) must extend and override the Car class as they need the functionalities of Car class. So, it is a good use case to use Abstract Class.

class Alto extends Car {

public void changeGears() {

System.out.println("Implement changeGears() method for Alto Car");

}

}

public interface Actor {

void perform();

}

public interface Producer {

void invest();

}

When we need to make a movie, we need an Actor & Producer, but they are not closely related.

Public class Movie implements Actor, Producer {

//doStuff to make a movie

}

In the next blog post, we will discuss other concepts in OOPs like Polymorphism,  Access Modifiers and super & this keywords.


Tags


You may also like

Groups attribute in TestNG 

Groups attribute in TestNG 
Leave a Reply

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}