Java OOPS
Java OOPS
1. Data Hiding
2. Abstraction
3. Encapsulation
4. Tightly Encapsulated Class
5. IS-A Relationship
6. HAS-A Relationship
7. Method Signature
8. Overloading
9. Overriding
10. Static Control Flow
11. Instance Control Flow
12. Constructors
13. Coupling
14. Cohesion
15. Type-Casting
➢ Data Hiding :
Outside Person can’t access our Internal Data Directly or our Internal Data should not go out directly. This OOP Feature is
nothing but data Hiding. After Validation/Authentication outside person can access our Internal data.
Example:
1. After Providing Proper Username and Password we can able to access our Gmail Inbox Information
2. Even Though we are valid Customer of the bank we can able to access our Account Information and
we can’t access others Account Information.
➢ Abstraction:
Hiding Internal Implementation and just highlight the set of services we are offering, is the concept of Abstraction. Ex:
Through Bank ATM GUI Screen , Bank people are highlighting the set of Services what they are offering without
highlighting Internal Implementation.
➢ Encapsulation:
The Process of binding data and corresponding methods into a single unit, is called Encapsulation.
Ex :
class Student
{
data members
+
Methods(behaviour)
}
Every java class is a Example of Encapsulation.
If any Component follows data hiding and abstraction, such type of component is said to be Encapsulated Component .
Encapsulation = Data hiding + Abstraction
Example:
class Student
{ Balance Enquiry
private double bal;
WELCOME TO ICICI BANK
public double Getbalance()
{
//Validation
return bal; Deposit
}
public void Setbalance(double bal)
{
//Validation
this.bal=bal;
}
}
➢ Tightly-Encapsulated class:
A class is said to Tightly Encapsulated if and only if Each and Every Variable Declared as “Private”. Weather class
corresponding getter and setter method or not and weather these methods are declared as public or not these things we
are not required to check.
class Student
{
Another Example:
class Student
{ Tightly Encapsulated
private double bal = 12.5;
class
}
class Student1 extends Student
{
int x =10; Normal class
}
class Studnet2 extends Student
{
private double bala = 13.5; Tightly Encapsulated
} class
➢ IS-A Relationship (Inheritance):
❖ Single Inheritance
❖ Multiple Inheritance
❖ Multi-level Inheritance
❖ Hierichaeal Inheritance
❖ Hybrid Inheritance
class Parent
{
void m1()
{
System.out.println("This is Parent");
}
}
class Child extends Parent
{
void m2()
{
System.out.println("This is Child");
}
}
class Test
{
public static void main(String[] args)
{
//Normal Object Creation
Parent p = new Parent();
p.m1();
p.m2();
//Upcasting
Parent p1 = new Child();
p1.m1();
p1.m2();
}
}
✓ Whatever Methods parent has , by default available to the child and hence on the child
reference we can call both parent and child class methods.
✓ Whatever Methods child has by default not available to the parent and hence on the parent
reference we can’t call child specific Methods.
✓ Parent reference can be used to hold child object but using that reference we can’t call child
specific methods but we can call the methods present in parent class.
✓ Parent reference can be used to hold child object but child reference cannot be used to hold
parent object
✓ Total Java API is Implemented based on Inheritance Concept.The Most Common Methods which
are applicable for any java Object are defined in Object class and hence every class in java is a
child of object either directly or indirectly . So that Object class methods by default available to
every java class without rewriting. Due to this Object class access root for all java Class.
✓ Throwable class defines most common Methods which are required for every Exception and
Error classes. Hence this class access a root for java Exception hirecherachy.
Multiple Inheritance :
A Java class can’t Extend more than one class at a time hence java won’t provide support for multiple inheritance in classes.
Note:
1. If our class doesn’t extends any other class then only our class is direct child class of object
Class A
{
void m1() Object
{
System.out.println("This is Parent");
}
A
} (SINGLE INHERITANCE)
2. If our class extends any other class then our class is indirect child class of Object.
Class A extends B
{
void m1() Object
{
System.out.println("This is Parent");
} B
}
(MULTI-LEVEL INHERITANCE)
A
3. Either Directly or indirectly java wont support to inheritance with respect to classes
B c
But Interface can extends any number of Interfaces simentanously.hence java provide support for multiple inheritance with
respect to interfaces.
Even though Multiple method declaration are available, but implementation is unique and hence there is no chance of
ambiguity problem in interfaces.
Cyclic Inheritance:
Class A extends A{
} A
Class A extends B{
} A
Class B extends B{
} B
➢ HAS-A Relationship:
Composition Aggregation
Without Existing Container Objects , if there is no chance of Without Existing Container Object, if there is a chance of existing
existing Contained Objects Then Container and Contained Objects contained Object then container and contained objects are weakly
are Strongly associated and this Strong association is nothing but associated and this weak association is nothing but Aggregation
Composition Example : Department Consists of several Professors , Without
Example: University consist of Several Departments , without existing Department there may be a chance of existing professor
existing university there is no chance of existing department Object hence department and professor object are Weakly
hence university and department are strongly associated and this associated and this weak association is nothing but Aggeregation
strong association is nothing but composition.
CSE EEE
Department Department
University
ECE Mech
Department Department
Professor1
Professor 2
Professor-n
Contained Object
Container Object
Note:
1. In Composition Objects are Strongly associated, where as in Aggregation Objects are Weakly associated
2. In Composition Container Object holds directly Contained Objects, whereas in aggregation container Objects holds just reference of
Contained Objects.
IS-A vs HAS-A?
If we want total functionality of a class automatically then we should go for IS-A If we want part of the functionality then we should go for HAS-A
Relationship Relationship
Example: Example:
Class Stud{
Public static void main(String[] args)
Person Student {
Student IS-A Person Person p = new Person();
class class P.m1(); Accessing Specific
p.m2(); Methods From
Person Class
}
}
Class Person{
//Set of 110 Methods
}
Method Signature:
Example:
➢ Overloading:
1. Two Methods are said to be overloaded if and only if both methods having same name but different
argument types.
2. In C language Method Overloading Concept is not available, hence we can’t declare multiple method
with same name but different argument types.
3. If There is change in argument type , then we should go for new method name which increases
complexity of Programming
Example in C: abs(int),labs(long),fabs(float)
4. But in Java we can declare Multiple methods with same name but different argument types such type of
methods are called Overloaded Methods
Class Test{
public void m1(){
System.out.println("This is m1");
}
public void m1(int i){
System.out.println("This is m1 with integer"); (Overloaded Methods)
}
✓ In Overloading Method Resolution always takes care by Compiler based on reference type hence Overloading is also Considered as
(Compile time Polymorphism) or (static Polymorphism) or (Early binding)
➢ Overriding:
Whatever Methods parent has by default available to the child through inheritance. If child class not satisfied with parent
class implementation then child is allowed to redefine that method based on its requirements. This process is called
Overriding. The Parent class methods which is overridden is called Overridden Method and the child class method which
is Overriding is called Overriding Method.
class Parent
{
public void property()
{
System.out.println(“Hi am Property”);
}
public void Marraige()→Overridden Method
{
System.out.println(“Jessie”); This Process is
}
called
} Overriding
class child extends Parent
{
public void Marraige()→Overriding Method
{
System.out.println(“Trisha”);
}
}
We are here creating an
public class Overriding{
object for parent through
child but if any method
public static void main(String[] args)
{
has been overriding from
Parent p = new child(); parent in the child then
p. Marriage(); // op- Trisha that method will be called
}
} in the runtime.
✓ In Overriding Method resolution always takes cares by JVM based on Run time Object and hence
Overriding is also considered Runtime Polymorphism or Dynamic Polymorphism or late binding.
✓ Rules for Overriding:
❖ In Overriding Method names and argument types must be matched. i.e)
Method signature must be same.
❖ In Overriding Return types must be same but this rule is applicable until 1.4
version only. From 1.5 version onwards we can take co-variant return types.
According to this child class Method return type need be same as parent
method return type.
class p
{
If we compile this in 1.4 public Object m1()
version, we will get error {
saying as System.out.println("this is m1");
return null;
F:\Java_codes\Temp_execu }
ted_java>javac -source 1.4 }
class c extends p
Over1.java {
public String m1()
Over1.java:11: error: m1() {
in c cannot override m1() in System.out.println("this is also m1");
return null;
p }
}
public String m1()
public class Over1{
^
public static void main(String[] args)
return type String is not {
System.out.println("hi this is
compatible with Object Overriding");
}
1 error
}
From 1.5 version, it will accept co-variant return types
Parent class Method return type:
/Stringbuffer..Etc
✓ Co-variant return type concept applicable only for Object types but not primitive types.
✓ Parent class private methods not available to the child and hence Overriding Concept is not
applicable for Private Methods.
✓ Based on Our requirement we can define exactly same private methods in child it is valid but
not overriding.
✓ We can’t Override Parent class final methods in child class, if we are tying to Override we will
get Compile time Error.
✓ Parent class Abstract methods we should Override in child class to provide Implementation
abstract class p
{
public abstract void m1();
}
class c extends p
{
public void m1()
{
//
}
}
✓ We can Override Non-abstract method as abstract .
class p
{
public void m1()
{
//
}
}
abstract c extends p
{
public abstract void m1();
}
✓ The Main advantage of the above approach is , we can stop the availability of parent method
implementation to the next level child classes
✓ In Overriding the following Modifiers Wont Keep any Restrictions.
1.)Synchronized
2.)native
3.)Strictfp
Parent Method Child Method
final → cannot be changed to ➔ nonfinal/final
What are possible ways a parent method
nonfinal → can be changed to ➔ final
can be overridden to child method: abstract → can be changed to ➔ non-abstract
synchronized → can be ➔ Non-Synchronized
changed to
native → can be changed to ➔ non-native
strictfp→can be changed to ➔ non-strictfp
✓ While Overriding we can’t reduce Scope of access Modifier but we can increase the Scope of Access Modifier.
class parent{
✓ if child class method throws any checked Exception Compulsory 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 Unchecked Exception.
Overridding.java:14: error: Marraige() in child cannot override Marraige() in parent
public void Marraige()throws Exception
^
overridden method does not throw Exception
1 error
Overriding With Respect to static Methods:
1. We can Override a Static Method as Non-static otherwise we will get compile Time Error.
class Test
{
public static void m1()
{
System.out.println("Am learning Overriding");
}
}
class Test1 extends Test
{
public void m1()
{
System.out.println("Am also learning");
}
}
Error:
StaticMethods.java:10: error: m1() in Test1 cannot override m1() in Test
public void m1()
^
overridden method is static
1 error
class Test
{
public void m1()
{
System.out.println("Am learning Overriding");
}
}
class Test1 extends Test
{
public static void m1()
{
System.out.println("Am also learning");
}
}
3. if Both Parent and child class Method are Static, then we Won’t get any Compile Time Error. It Seems
Overriding Concepts Applicable for static Methods, but it is not Overriding and it is Method hiding.
Method Hiding:
All Rules of Method hiding are exactly same as Overriding except the following differences ,
If Both parent and child class Methods are Non-static then, it will become Overriding.
1. We can override var-arg method with another var-arg method only. If we are trying to override with
normal method then it will become overloading but not overriding.
class parent
{
public void m1(int... x)
{
System.out.println("Parent");
}
}
class child extends parent
{
public void m1(int x)
{
System.out.println("child");
}
}
➢ Coupling:
➔ The Degree of the dependency between the components is called Coupling.
The Above Components are said to be Tightly coupled with each other, because dependency between the
components is More.
Tightly coupling is not a Good Programming Practice, because it has several serious disadvantages,
1. Without affecting remaining components we can’t modify any components and hence enhancement will
become difficult.
2. It suppresses re-usability.
3. It reduces Maintainability of the application
Hence, we have to maintain dependency between the components as less as Possible.ie) loosely
Coupling is a Good Programming Practice.
➢ Cohesion:
For Every Component a Clear Well defined Functionality is defined, then that component is said to be follow High
Cohesion or else if the component is not explained clearly then it is called Low cohesion.
High Cohesion is always a Good Programming Practice , because it has several advantages,
1. Without Affecting Remaining Components , we can Modify any component. Hence Enhancement will become
Easy.
2. It Promotes Reusability of the Code. Wherever Validation is required we can reuse the same Validate Servlet
without Rewriting.
3. It Improves Maintainability of the Application
Note: Loosely Coupling and High Cohesion are Good Programming Practices.
class Base
{
static int i =10;
static
{
m1();
System.out.println("First static block");
}
public static void main(String[] args)
{
m1();
System.out.println("Main Method");
}
public static void m1()
{
System.out.println(j);
}
static
{
System.out.println("Second static block");
}
static int j=20;
}
Output :
0
First static block
Second static block
20
Main Method
Static Blocks:
1. Static block will be Executed at the time of class Loading. Hence at the time of class loading if we want to
perform any activity, we have define that inside static block.