OOPS

Object-Oriented Programming

I hope you probably know, object-oriented programming are very important in Java. Without having an idea about OOPS , We will not be able to design program in the object-oriented model because it simplifies software development and maintenance.

There are two types of  programming models. They are procedure oriented programming language and object oriented programming language. If we represent the data using procedural oriented programming languages then there is no security for the data which we represent. Java is Object oriented Programming language where as C, C++ are procedure oriented programming language.

  • Object, Class , Method, Variable
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Object- Everything in the real-world is an Objects like a book, laptop, cloth,shoe etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects.Lets see the concepts of OOPS.

 Class“A class is a way of binding the data and associated methods in a single unit”. Any Java program if we want to develop then that should be developed with respective class only i.e., without class there is no JAVA program. In object oriented programming’s, generally we write two types of methods.methods. They are member methods and non-member.

A member method is one which is comes under the scope of the class. In JAVA we use only member methods.Non-member methods are those which are not comes under the scope of the class. JAVA does not allow non-member methods at all

Here we will learn in depth concept about OOPS. In this post, we will learn what exactly Java Oops & how we need to use it.Lets divide this in 16 important concepts with examples. The following diagram shows a list of OOPS concepts in Java that we will be taking a look at in this article.

Data Hiding

Our internal data should not go out directly that is outside person can’t access our internal data directly.By using private modifier we can implement data hiding.

After providing proper username and password only, we can access our Account information. The main advantage of data hiding is for security.
Note: Recommended modifier for data members is private.

Abstraction

Hide internal implementation and just highlight the set of services, ¡s called abstraction. By using abstract classes and interfaces we can implement abstraction.

Example:
By using ATM GUI screen bank people are highlighting the set of services what they are offering without highlighting internal implementation.

The main advantages of Abstraction are:

  • We can achieve security as we are not highlighting our internal implementation.(i.e., outside person doesn’t aware our internal implementation.)
  • Enhancement will become very easy because without effecting end user we can able to perform any type of changes in our internal system.
  • It provides more flexibility to the end user to use system very easily.
  • It improves maintainability of the application.
  • It improves modularity of the application.
  • It improves easy ness to use our system. By using interfaces (GUI screens) we can implement abstraction

Encapsulation

Binding of data and corresponding methods into a single unit is called Encapsulation. If any java class follows data hiding and abstraction such
type of class is said to be encapsulated class.

Encapsulation = Data Hiding + Abstraction

Example:

The main advantages of encapsulation are:

  • We can achieve security.
  • Enhancement will become very easy.
  • It improves maintainability and modularity of the application.
  • It provides flexibility to the user to use system very easily

The main disadvantage of encapsulation is it increases length of the code and slows down execution. Every data member should be declared as private and for every member we have to maintain getter & Setter methods.

Tightly encapsulated class

A class is said to be tightly encapsulated if and only if every variable of that class declared as private whether the variable has getter and setter methods are not, and whether these methods declared as public or not, these checking are not required to perform.

Example

Which of the following classes are tightly encapsulated?

Which of the following classes are tightly encapsulated?

Note:
If the parent class is not tightly encapsulated then no child class is tightly encapsulated.

IS-A Relationship (Inheritance)

  • Also known as inheritance.
  • By using “extends” keywords we can implement IS-A relationship.
  • The main advantage of IS-A relationship is reusability.

Example

Conclusion:

  • Whatever the parent has by default available to the child but whatever the child has by default not available to the parent. Hence on the child reference we can call both parent and child class methods. But on the parent reference we can call only methods available in the parent class and we can’t call child specific methods.
  • Parent class reference can be used to hold child class object but by using that reference we can call only methods available in parent class and child specific methods we can’t call.
  • Child class reference cannot be used to hold parent class object.

Example:

The common methods which are required for housing loan, vehicle loan, personal loan and education loan we can define into a separate class ¡n parent class loan. So that automatically these methods are available to every child loan class.

Example:

For all java classes the most commonly required functionality is define inside object class hence object class acts as a root for all java classes.
For all java exceptions and errors the most common required functionality defines inside Throwable class hence Throwable class acts as a root for exception hierarchy.

Multiple Inheritance:

Having more than one Parent class at the same level is called multiple inheritance.

Any class can extend only one class at a time and can’t extends more than one class simultaneously hence java won’t provide support for multiple inheritance.

But an interface can extends any no. Of interfaces at a time hence java provides support for multiple inheritance through interfaces.

If our class doesn’t extends any other class then only our class is the direct child class of object.

If our class extends any other class then our class is not direct child class of object, It is indirect child class of object, which forms multilevel inheritance.

Why java won’t provide support for multiple inheritance?
There may be a chance of raising ambiguity problems.

Ambiguity Problem
Why ambiguity problem won’t be there in interfaces?

Interfaces having dummy declarations and they won’t have implementations hence no ambiguity problem.

Cyclic inheritance

Cyclic inheritance is not allowed in java.

HAS-A Relationship

  • HAS-A relationship is also known as composition (or) aggregation.
  • There is no specific keyword to implement HAS-A relationship but mostly we can use new operator.
  • The main advantage of HAS-A relationship is reusability.

class Car HAS-A engine reference

The main disadvantage of HAS-A relationship increases dependency between the components and creates maintains problems.

Composition vs Aggregation:

Composition:
Without existing container object if there ¡s no chance of existing contained objects then the relationship between container object and contained object is called composition which is a strong association.

Example:
University consists of several departments whenever university object destroys automatically all the department objects will be destroyed that is without existing university object there ¡s no chance of existing dependent object hence these are strongly associated and this relationship is called
composition.

Aggregation:
Without existing container object if there is a chance of existing contained objects such type of relationship is called aggregation. In aggregation objects have weak association.

Example:
Within a department there may be a chance of several professors will work whenever we are closing department still there may be a chance of existing professor object without existing department object the relationship between
department and professor is called aggregation where the objects having weak association.

Note:
In composition container, contained objects are strong associated, and but container object directly holds contained objects directly, but in Aggregation container are weakly associated and container object are weakly associated and container object just holds the reference of contained objects.

Method Signature

In java, method signature consists of name of the method followed by argument types.

In java return type is not part of the method signature. Compiler will use method signature while resolving method calls.

Within the same class we can’t take 2 methods with the same signature otherwise we will get compile time error.

Polymorphism

Polymorphism is nothing but “many forms”.

Same name with different forms is the concept of polymorphism.
Example1: We can use same abs() method for int type, long type, float type etc.

Example:
1. abs(int)
2. abs(long)
3. abs(float)

Example2:
We can use the parent reference to hold any child objects. We can use the same List reference to hold ArrayList object, LinkedList object, Vector object, or Stack object.

Example:
1 . List l = new ArrayList();
2. List l = new Linked List();
3. List l = new Vector();
4. List l = new Stack();

Pillars of OOPS

Inheritance talks about reusability.
Polymorphism talks about flexibility.
Encapsulation talks about security.

Overloading:

  • Two methods are said to be overload if and only if both having the same name but different argument types.
  • In ‘C’ language we can’t take 2 methods with the same name and different types. If there is a change in argument type compulsory we should go for new method name.
  • Lack of overloading in “C” increases complexity of the programming.
  • But in java we can take multiple methods with the same name and different argumenttypes.
  • Having the same name and different argument called method overloading types is called method overriding.
  • All these methods are considered as overloaded methods.
  • Having overloading concept in java reduces complexity of programming.

Conclusion:
In overloading compiler is responsible to perform method resolution(decision) based on the reference type(but not based on run time object. Hence overloading is also considered as compile time polymorphism (or) static polymorphism (or) early Binding.

Case 1: Automatic promotion in overloading.

In overloading if compiler is unable to find the method with exact match we won’t get any compile time error immediately.

1st compiler promotes the argument to the next level and checks whether the matched method is available or not if ¡t is available then that method will be considered if it is not available then compiler promotes the argument once
again to the next level. This process will be continued until all possible promotions still if the matched method is not available then we will get compile time error. This process is called automatic promotion in overloading.

The following are various possible automatic promotions in overloading.

Case2:

Note:
While resolving overloaded methods exact match will always get high priority, While resolving overloaded methods child class will get the more priority than parent class

Case3:

Case4:

Case5:

In general var-arg method will get less priority that is if no other method matched then only var-arg method will get chance for execution it is almost same as default case inside switch.

Case6:

In overloading method resolution is always based on reference type and runtime object won’t play any role in overloading.

Overriding:

  • Whatever the Parent has by default available to the Child through inheritance, if the Child is not satisfied with Parent class method implementation then Child is allow to redefine that Parent class method in Child class in its own way this process is called overriding.
  • The Parent class method which is overridden is called overridden method.
  • The Child class method which is overriding is called overriding method.

In overriding method resolution is always takes care by JVM based on runtime object hence overriding is also considered as runtime polymorphism or dynamic polymorphism or late binding. The process of overriding method resolution is also known as dynamic method dispatch.
Note:
In overriding runtime object will play the role and reference type is dummy.

Rules for overriding:

  • In overriding method names and arguments must be same. That is method signature must be same.
  • Until 1 .4 version the return types must be same but from 1 .5 version onwards covariant return types are allowed. According to this Child class method return type need not be same as Parent class method return type its Child type also allowed.

c:> javac -source 1.4 Parent.java //Error

It is valid in “1.5” but invalid in “1.4”.

Co-variant return type concept is applicable only for object types but not for primitives. Private methods are not visible in the Child classes hence
overriding concept is not applicable for private methods. Based on own requirement we can declare the same Parent class private method in child class also. It is valid but not overriding.

Parent class final methods we can’t override in the Child class.

Output:
Compile Time Error:
methodOne() in Child cannot override method One() in Parent; overridden method is final Parent class non final methods we can override as final in
child class. We can override native methods in the child classes.
We should override Parent class abstract methods in Child classes to provide the implementation.

We can override a non-abstract method as abstract this approach is helpful to stop availability of Parent method implementation to the next level child classes.

Example

Synchronized, strictfp, modifiers won’t keep any restrictions on overriding.

While overriding we can’t reduce the scope of access modifier.

Example:

Checked Vs Un-Checked Exceptions:
The exceptions which are checked by the compiler for smooth execution of the program at runtime are called checked exceptions.
The exceptions which are not checked by the compiler are called un-checked exceptions. RuntimeException and its child classes, Error and its child classes are unchecked except these the remaining are checked Exception.

Rule:
While overriding if the child class method throws any checked exception compulsory the parent class method should throw the same checked exception or its parent otherwise we will get compile time error, but there are no restrictions for un-checked exceptions.

Output:

Compile time error:

methodOne() in Child cannot override methodOne() in Parent; overridden method does not throw java.lang.Exception.

Overriding with respect to static methods:
Case 1
:
We can’t override a static method as non-static.

Example:

Output:
CE: methodOne() in Child can’t override methodOne() in Parent ; overridden method is static.

Case 2:
Similarly we can’t override a non static method as static

Case 3:

It is valid. It seems to be overriding concept is applicable for static methods but it is not overriding it is method hiding.

Method hiding:
All rules of method hiding are exactly same as overriding except the following differences.

Example:

Note:
If both Parent and Child class methods are non-static then it will become overriding and method resolution is based on runtime object. In this case the output is Parent class Child class Child class.

Overriding with respect to Var-arg methods:
A var-arg method should be overridden with var-arg method only. If we are trying to override with normal method then it will become overloading but not overriding.

In the above program if we replace child class method with var-arg then ¡t will become overriding. In this case the output is
Parent class
Child class
Child class

Overriding with respect to variables:
Overriding concept is not applicable for variables.Variable resolution is always takes care by compiler based on reference type.

Example:

Note:
In the above program Parent and Child class variables, whether both are static or non static whether one is static and the other one is non static there is no change answer.

Differences between overloading and overriding?

Note:
1. In overloading we have to check only method names (must be same) and arguments (must be different) the remaining things like return type extra not required to check.

2. But In overriding we should compulsory check everything like method names, arguments, return types, throws keyword, modifiers etc.
Consider the method in parent class

Parent: public void methodOne(int i)throws IOException

In the child class which of the following methods we can take..
1. public void methodOne(int i)//valid(overriding)
2. private void methodOne()throws Exception //Invalid (Overriding)

3. public native void methodOne(int i);//valid(overriding)
4. public static void methodOne(double d)//valid(overloading)
5. public static void methodOne(int i)
Compile time error:
methodOne(int) in Child cannot override methodOne(int) in Parent; overriding
method is static
6. public static abstract void methodOne(float f)

Compile time error:
1. illegal combination of modifiers: abstract and static
2. Child is not abstract and does not override abstract method
methodOne(float) in Child.

What is the difference between ArrayList l=new ArrayList() & List l=new ArrayList?

In how many ways we can create an object? (or) In how many ways get an object in java?

1. By using new Operator

Test t = new Test();
2. By using newInstance() //Reflection Mechanism

Test t=(Test)Class.forName(”Test”).newInstance();
3. By using Clone():
Test t1 = new Test();
Test t2 = (Test)tl .Clone();

4.By using Factory methods:
Runtime r = Runtime.getRuntime;
DateFormat df = DateFormat.getInstance();

5. By using Deserialization:

FilelnputStream fis = new File InputStream(”abc.ser”);
ObjectlnputStream ois = new ObjectlnputStream(fis);
Test t = (Test)ois.readObject();

Static Control Flow

Output:

c:\data>javac Base.java
c:\data>java Base
0
First static block
Second static block

20

Main method

Read indirectly write only state (or) RIWO:
Within the static block if we are trying to read any variable then that read is considered as direct read If we are calling a method, and within the method if we are trying to read a method , that read is called Indirect read
If a variable is in RIWO state then we can’t perform read operation directly otherwise we will get compile time error saying “ illegal forward reference”

Static Control Flow Parent to Child Relationship

Output:
c:\data>java
0

Base static block
0

Derived first static block
Derived second static block
200
Derived main Output:
C:\data>java Base
0
Base static block
20
Basic main

Whenever we are executing Child class the following sequence of events will be performed automatically.

1. Identification of static members from Parent to Child. [1 to 11]
2. Execution of static variable assignments and static blocks from Parent to Child. [12 to 22]
3. Execution of Child class main() method.[23 to 25].

Note:
Whenever we are loading child class automatically the parent class will be loaded but whenever we are loading parent class the child class don’t be loaded automatically.

Static Block:
Static blocks will be executed at the time of class loading hence if we want to perform any activity at the time of class loading we have to define that activity inside static block. Within a class we can take any no. Of static blocks and all these static blocks will be executed from top to bottom.

Example:
The native libraries should be loaded at the time of class loading hence we have to define that activity inside static block.

Every JDBC driver class internally contains a static block to register the driver with Driver Manager hence programmer is not responsible to define this explicitly.

Static Control
Without using main method is it possible to print some statements to the console?
Ans : Yes, by using static block.

Example:

Output:
Hello i can print

Without using main method and static block is it possible to print some statements to the console?

Example:1

Output: Hello i can print

Example2:

Output: Hello i can print

Example:3

Output: Hello i can print

Without using System.out.println() statement is it possible to print some statement to the console?

Note:
Without using main method we can able to print some statement to the console, but this rule is applicable until 1.6 version from 1.7 version onwards to run java program main() method is mandatory. It is valid in 1.6 version but invalid or won’t run in 1 .7 version

It is valid upto 1.6 v but invalid or won’t run in 1.7 v .

Instance Control Flow

Whenever we are executing a java class static control flow will be executed. In the Static control flow, whenever we are creating an object the following sequence of events will be performed automatically.

1. Identification of instance members from top to bottom (3 to 8).
2. Execution of instance variable assignments and instance blocks from top to bottom (9 to 14).
3. Execution of constructor.

Static control flow is one time activity and it will be executed at the time of class loading, but instance control flow is not one time activity for every object creation it will be executed.

Instance control flow in Parent to Child Relationship:

Output:
E:scjp>javac Child.java
E:scjp>java Child
0
Parent first instance block
Parent class constructor
0

Child first instance block
Child second instance block
Child class constructor
Child class main method

Whenever we are creating child class object the following sequence of events will be executed automatically.

1. Identification of instance members from Parent to Child.
2. Execution of instance variable assignments and instance block only in Parent class.
3. Execution of Parent class constructor.
4. Execution of instance variable assignments and instance blocks in Child class.
5. Execution of Child class constructor.

Note:
Object creation is the most costly operation in java and hence if there is no specific requirement never recommended to create objects.

Example:1

Output:
1
3
2

Output:
1
3
2

But from the instance area we can access instance members directly.
Static members we can access from anywhere directly because these are identified already at the time of class loading only.

Constructor

1.Object creation is not enough compulsory we should perform initialization then only the object is in a position to provide the response properly.
2. Whenever we are creating an object some piece of the code will be executed automatically to perform initialization of an object this piece of the code is nothing but constructor.
3. Hence the main objective of constructor is to perform initialization of an object.

Constructor Vs Instance Block:
1. Both instance block and constructor will be executed automatically for every object creation but instance block 1st followed by constructor.
2. The main objective of constructor is to perform initialization of an object.

3. Other than initialization ¡f we want to perform any activity for every object creation we have to define that activity inside instance block.
4. Both concepts having different purposes hence replacing one concept with another concept ¡s not possible.
5. Constructor can take arguments but instance block can’t take any arguments hence we can’t replace constructor concept with instance block.
6. Similarly we can’t replace instance block purpose with constructor.

Demo program to track no of objects created for a class:

Test Class

Rules to write constructors:
1. Name of the constructor and name of the class must be same.
2. Return type concept is not applicable for constructor even void also by mistake if we are declaring the return type for the constructor we won’t get any compile time error and runtime error compiler simply treats it as a method.

Example:
class Test{
void test(){ {} }
//it is not a constructor and it is a method

It is legal (but stupid) to have a method whose name is exactly same as class name. The only applicable modifiers for the constructors are public, default, private, protected.
If we are using any other modifier we will get compile time error.

Output:
Modifier static not allowed here

Default Constructor:
1. For every class in java including abstract classes also constructor concept is applicable.
2. If we are not writing at least one constructor then compiler will generate default constructor.
3. If we are writing at least one constructor then compiler won’t generate any default constructor. Hence every class contains either compiler generated constructor (or) programmer written constructor but not both simultaneously

Prototype of Default Constructor:
1. It is always no argument constructor.
2. The access modifier of the default constructor is same as class modifier. (This rule is applicable only for public and default).
3. Default constructor contains only one line. Super(); it is a no argument call to super class constructor.

super() vs this():
The 1st line inside every constructor should be either super() or this() if we are not writing anything compiler will always generate super().

Case 1:
We have to take super() (or) this() only in the 1st line of constructor. If we are taking anywhere else we will get compile time error.

Output:
Compile time error. Call to super must be first statement in constructor.

Case 2:
We can use either super() (or) this() but not both simultaneously.

Output:
Compile time error.
Call to this must be first statement in constructor

Case 3:
We can use super() (or) this() only inside constructor. If we are using anywhere else we will get compile time error.

Output:
Compile time error.
Call to super must be first statement ¡n constructor

That is we can call a constructor directly from another constructor only.

Output:
Compile time error.
Non-static variable super cannot be referenced from a static context

Overloaded constructors:
A class can contain more than one constructor and all these constructors having the same name but different arguments and hence these constructors are considered as overloaded constructors.

Parent class constructor by default won’t available to the Child. Hence Inheritance concept is not applicable for constructors and hence overriding concept also not applicable to the constructors. But constructors can be overloaded. We can take constructor in any java class including abstract class also but we can’t take constructor inside interface.

Example:
We can’t create object for abstract class but abstract class can contain constructor what is the need?
Abstract class constructor will be executed for every child class object creation to perform initialization of child class object only.

Which of the following statement is true?
1. Whenever we are creating child class object then automatically parent class object will be created.(false) .Whenever we are creating child class object then parent class constructor will be executed.(true) .

Case1:

Recursive method call is always runtime exception where as
Recursive constructor invocation is a compile time error.

Note:
Recursive functions:
A function is called using two methods (types).
1. Nested call
2. Recursive call

Nested call:
Calling a function inside another function is called nested call.
In nested call there is a calling function which calls another function(called function).

Recursive call:
Calling a function within same function is called recursive call.
In recursive call called and calling function is same.

Note:
Compiler is responsible for the following checking.
1. Compiler will check whether the programmer wrote any constructor or not. If he didn’t write at least one constructor then compiler will generate default constructor.
2. If the programmer wrote any constructor then compiler will check whether he wrote super() or this() in the 1st line or not. If his not writing any of these compiler will always write (generate) super().
3. Compiler will check is there any chance of recursive constructor invocation. If there is a possibility then compiler will raise compile time error.

If the Parent class contains any argument constructors while writing Child classes we should takes special care with respect to constructors.Whenever we are writing any argument constructor it is highly recommended to write no argument constructor also.

Case:3

Output:
Compile time error
Unreported exception java.io.IOException in default constructor.

Coupling

The degree of dependency between the components is called coupling.

Example

The above components are said to be tightly coupled to each other because the dependency between the components is more.
Tightly coupling is not a good programming practice because it has several serious disadvantages.

1 . Without effecting remaining components we can’t modify any component hence enhancement (development) will become difficult.
2. It reduces maintainability of the application.
3. It doesn’t promote reusability of the code. It is always recommended to maintain loosely coupling between the components.

Cohesion

For every component we have to maintain a clear well defined functionality such type of component is said to be follow high cohesion.

High cohesion is always good programming practice because it has several advantages.
1. Without effecting remaining components we can modify any component hence enhancement will become very easy.
2. It improves maintainability of the application.
3. It promotes reusability of the application.(where ever validation is required we can reuse the same validate servlet without rewriting)

Note:
It is highly recommended to follow loosely coupling and high cohesion

Object Type Casting

Parent class reference can be used to hold Child class object but by using that reference we can’t call Child specific methods.

Output:
C.E:cannot find symbol,
symbol : method lengthQ,
location: class java.lang.Object
Similarly we can use interface reference to hold implemented class object

Example:

Runnable r=new Thread O;
Type casting syntax:

Compile time checking:
Rule 1 : The type of ‘d” and “c” must have some relationship [either Child to Parent (or) Parent to Child (or) same type] otherwise we will get compile time error saying inconvertible types

Rule 2:

“C” must be either same (or) derived type of “A” otherwise we will get compile time error saying incompatible types.

Example:1

Runtime Checking:

The Underlying object type of “d” must be either same(or)derived type of “c” otherwise we will get runtime exception saying ClassCastException.

Basel b=new Derived2();//valid
Object o=(Base1)b;//valid

Object ol =(Base2)o;//invalid
Object o2=(Base2)b;//invalid
Base2 b1 =(Base1)(new Derived1());//invalid
Base2 b2=(Base2)(new Derived3());//valid
Base2 b2=(Base2)(new Derived1());//invalid

Through Type Casting just we are converting the type of object but not object itself that is we are performing type casting but not object casting.

Through Type Casting we are not create any new objects for the existing objects we are providing another type of reference variable(mostly Parent type).

Example1:

It is overriding and method resolution is based on runtime object
C c=new C();
c.methodOne();//c
((B)c) . method One();//c
((A)((B)c)).methodOne();//c

C c=new C();
System.out.println(c.x);//999
System.out.println(((B)c).x);//888
System.out.println(((A)((B)c)).x);//777

Variable resolution is always based on reference type only. If we are changing variable as static then also we will get the same output.

Singleton Classes

For any java class if we are allow to create only one object such type of class is said to be singleton class.

Example:
1) Runtime class
2) ActionServlet
3) ServiceLocator
4) BusinessDelegate

Advantage of Singleton class:
If the requirement is same then instead of creating a separate object for every person we will create only one object and we can share that object for every required person we can achieve this by using singleton classes. That is the main advantages of singleton classes are Performance will be improved and memory utilization will be improved.

Creation of our own singleton classes:
We can create our own singleton classes for this we have to use private constructor, static variable and factory method.

Which of the following is true?
1 . The name of the constructor and name of the class need not be same.(false)
2. We can declare return type for the constructor but it should be void. (false)
3. We can use any modifier for the constructor. (false)
4. Compiler will always generate default constructor. (false)
5. The modifier of the default constructor is always default.(false)
6. The 1st line inside every constructor should be super always. (false)
7. The 1st line inside every constructor should be either super or this and if we are not writing anything compiler will always place this().(false)
8. Overloading concept is not applicable for constructor.(false)
9. Inheritance and overriding concepts are applicable for constructors. (false)

10. Concrete class can contain constructor but abstract class cannot. (false)
11. Interface can contain constructor. (false)

12. Recursive constructor call is always runtime exception.(false)
13. If Parent class constructor throws some un-checked exception compulsory Child class constructor should throw the same un-checked exception or it’s Parent. (false)
14. Without using private constructor we can create singleton class. (false)