0% found this document useful (0 votes)
21 views15 pages

Java OOPS

The document provides an overview of key concepts in Java Object-Oriented Programming (OOP), including data hiding, abstraction, encapsulation, inheritance (IS-A and HAS-A relationships), method signatures, overloading, and overriding. It explains the importance of encapsulation for security and maintainability, the differences between composition and aggregation, and the rules governing method overriding. Additionally, it discusses the implications of inheritance, including the limitations of multiple inheritance in Java and the use of interfaces.

Uploaded by

khaja96355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views15 pages

Java OOPS

The document provides an overview of key concepts in Java Object-Oriented Programming (OOP), including data hiding, abstraction, encapsulation, inheritance (IS-A and HAS-A relationships), method signatures, overloading, and overriding. It explains the importance of encapsulation for security and maintainability, the differences between composition and aggregation, and the rules governing method overriding. Additionally, it discusses the implications of inheritance, including the limitations of multiple inheritance in Java and the use of interfaces.

Uploaded by

khaja96355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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.

The Main Advantages of Abstraction are,


1. We can achieve Security because we are highlighting our internal implementation
2. Without affecting outside person we can able to perform any type of changes in our internal system and
hence enhancement will become easy
3. It Improves maintainability of the application
4. It improves easiness to use our system

By using Interfaces and Abstract classes we can Implement abstraction.

➢ 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;
}
}

Both Data hiding and Abstraction is Achieved above.

The Main Advantages of Encapsulation are,

1. We can achieve Security


2. Enhancement will become easy
3. It improves Maintainability of the application

The Main Disadvantage of Encapsulation is ,

1. It Increases length of the code and slows down Execution

➢ 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
{

private double bal;


Tightly Encapsulated
public double Getbalance()
{ class
//Validation
return bal;
}
}

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):

1. It is also known as Inheritance


2. The main advantage IS-A relationship is Code Reusability
3. By using extends keyword we can implement IS-A Relationship

❖ 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();

//Normal Object Creation


Child c = new Child();
c.m1();
c.m2();

//Upcasting
Parent p1 = new Child();
p1.m1();
p1.m2();

//Downcasting -- Not Possible in java


Child c1 = new Parent();

//To do Downcasting, we need to have reference of parent


Child c2 = (p1)Child;
c2.m1();
c2.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.

Class A extends B,C


{
void m1()
{ Can’t extends Two
System.out.println("This is Parent"); 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

Why java Won’t provide support multiple Inheritance?


Their may be a chance of Ambiguity Problem, hence java won’t provide support multiple inheritance.

B c

But Interface can extends any number of Interfaces simentanously.hence java provide support for multiple inheritance with
respect to interfaces.

Why Ambiguity Problem won’t be their in interfaces?

Even though Multiple method declaration are available, but implementation is unique and hence there is no chance of
ambiguity problem in interfaces.

Strictly Speaking, Through Interfaces we wont get any inheritance.

Cyclic Inheritance:

It is not allowed in java, also it is not required

Class A extends A{

} A
Class A extends B{

} A
Class B extends B{

} B

➢ HAS-A Relationship:

1. HAS-Relationship is also known as Composition or Aggerigation


2. There is no Specific keyword to implement HAS-A Relation , but most of the times we are depending on
“new” keyword.
3. The Main Advantage of HAS-A Relationship is Reusability of the code

Class car Class Engine


{ {
public static void main(String[] args)
{ //Will list out Engine Specific Functionality Car HAS-A Enginee Reference
Engine e = new Engine();
} }
}
Difference b/w Composition and Aggregation:

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

Contained Objects Department


Container Objects

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?

IS-A Relation HAS-A Relation

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:

✓ In java Method Signature consist of Method name followed by argument types


✓ Example : public static int m1(int i,float f) →m1(int,float) //Method signature//
✓ Return type is part of method signature in java
✓ Compiler will use Method signature to resolve Method calls

Example:

public void m1(int i){

System.out.println("This is m1 with integer");

Method Signature : m1(int)

➢ 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

Example in Java : abs(int),abs(long),abs(long)

5. Having Overloading Concept in java reduces Complexity of Programming


Example :

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)
}

public void m1(double d){


System.out.println("This is m1 with double");
}
}
Class Demo{

public static void main(String[] args)


{
Test t = new Test();
t.m1();
t.m1(10);
t.m1(10.5);
}
}

✓ 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:

Object Number String

(Possible return types) (Possible return types) (Impossible return types)

Object/String Number/Integer Object


Child 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{

public void property()


{
System.out.println("This is My Property");
}
public void Marraige()
{
System.out.println("Trisha");
}
}
class child extends parent
{
void Marraige()
{
System.out.println("Nayanthara!");
}
}

public class Overridding{

public static void main(String[] args)


{
parent p = new child();
p.Marraige();
}
}

if we run this Program we will get Error as :


Overridding.java:14: error: Marraige() in child cannot override Marraige() in parent
void Marraige()
^
attempting to assign weaker access privileges; was public
1 error

Parent class Method Child class Method


Public→can be overridden to Public

Protected→can be Overridden to Protected/public

<default>→can be Overridden to <default>/protected/public

Private→(Impossible) Overriding Concepts not applicable for Private


Methods

✓ 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");
}
}

public class StaticMethods


{
public static void main(String[] args)
{
Test tez = new Test1();
tez.m1();
}
}

Error:
StaticMethods.java:10: error: m1() in Test1 cannot override m1() in Test
public void m1()
^
overridden method is static
1 error

2. We cannot Override a Non-static Method as Static.

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");
}
}

public class StaticMethods


{
public static void main(String[] args)
{
Test tez = new Test1();
tez.m1();
}
}
Error:
StaticMethods.java:10: error: m1() in Test1 cannot override m1() in Test
public static void m1()
^
overriding method is static
1 error

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 ,

Method hiding Overriding


Both Parent and Child class Method should be Both Parent and Child class Method should be
static non-static
Compiler is responsible for Method resolution JVM is always responsible for Method resolution
based on reference type based on run type Object.
It is also known as Compile time/static It is also known as Runtime/Dynamic
Polymorphism/early binding Polymorphism / late binding

If Both parent and child class Methods are Non-static then, it will become Overriding.

Overriding with respect to var-arg:

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");
}
}

public class Vararg


{
public static void main(String[] args)
{
parent p = new child();
p.m1(10);
}
}
Output – Parent.

➢ Coupling:
➔ The Degree of the dependency between the components is called Coupling.

➔ if dependency is more then it is considered as Tightly Coupling.

➔ if the dependency is less then it is considered as loosely Coupling.

class A class B class c class D


{ { { {
static int i=B.j; static int j = C.k; static int k = D.m1(); public static int m1()
} } } {
return 10;
}
}

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.

➢ Object Type Casting:


We can use parent Reference to hold child Object. Ex) Object obj = new String(“Koushick”);
We can use Interface Reference to hold Implemented class Object Ex) Runnable r = new Thread();

Example 1 : Object ob = new String(“Koushick”);


StringBuffer b = (StringBuffer) ob; Valid

Example 2 : String s = new String(“Koushick”); Invalid. Found: String,


StringBuffer bb = (StringBuffer) s;
required: String Buffer.

➢ Static Control Flow:


Whenever we are executing a Java Class, the following Sequence of steps will be executed as the part of static control
flow.
1. Identification of static members from top to bottom
2. Execution of static variable assignments and static blocks from top to Bottom
3. Execution of main Method.

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

Read Indirectly and Write Only:


1. Inside static block if we are trying to read a variable , that read operation is called direct read.
2. if we are calling a Method, and within that method if we are trying to read a variable that read
operation is called Indirect Read.
3. if a variable is just identified by the JVM and Original value not yet assigned then the variable is said
to be in Read Indirectly and Write only state.[RIWO]
4. if a variable is in Read indirectly write only state, then We can’t Perform direct read. But we can
Perform Indirect read
5. if we are trying to read directly then we get Compile time Error saying “Illegal Forward reference”

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.

You might also like