[go: up one dir, main page]

0% found this document useful (0 votes)
4 views13 pages

CH 5 Oops

The document outlines key concepts of Object-Oriented Programming (OOP) including data hiding, abstraction, encapsulation, inheritance, polymorphism, and exception handling. It explains the differences between method overloading and overriding, the role of constructors, and the concept of singleton classes. Additionally, it discusses the implications of access modifiers and relationships such as composition and aggregation.

Uploaded by

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

CH 5 Oops

The document outlines key concepts of Object-Oriented Programming (OOP) including data hiding, abstraction, encapsulation, inheritance, polymorphism, and exception handling. It explains the differences between method overloading and overriding, the role of constructors, and the concept of singleton classes. Additionally, it discusses the implications of access modifiers and relationships such as composition and aggregation.

Uploaded by

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

***OOPS*** [oop is volume 1 page [184 TO 244]

==========

*DATA HIDING:- [using private modifier , for security purpose]


--------------
>outside person can not access our internal class data directally,
By using private modifier we can impl data hiding.
Ex: class Account {

private double balance;


}

> using hiding concept we achive security.


> recommended modifier for data mem is private.

*ABSTRACTION :-
--------------
>Hiding internal impl and just highlight the set of services, is called
abstraction.
>by using using abstract classes and interfaces we can impl abstraction.

Ex: ATM GUI -> bank people are highlighting only the set of services .

ADVANTAGE OF ABSTRACTION:-
--------------------------
> we achive security.
> provide flexibility to end user, improve modularity, and maintainablilty.

*ENCAPSULATION: [data hiding + abstraction]


--------------
>Binding of data and corresponding methods into a single unit is called
Encapsulation
>if any java class follows data hiding and abstract such type of class is said to
be encapsulation class.

Note:-Every data member (vars) declared as private and for every var or mem
maintain getter and setter methods.

*ADVANTAGE OF ENCAPSULATION:-
-----------------------------
>achiving security.

** TIGHTLY ENCAPSULATED CLASS:-


>if and only if every var of that class declared as private
weather the var has getter and setter or not, or
whether these methods declared as public or not,

Note:- if we extends any class in herarchy , and if any parent class var not
declare private var that extended by our class
then our class is also not tight encapsulated class (mean all class should
have private var.)

* INHERITANCE / [IS-A] : RELATIONSHIP : (for code reusability)


------------------------------------------
>its also known as inheritance, by using extends kw we impl IS- A relationship.
> we achive code reusability by inheritance.

IMP NOTE:-
1-whatever parent has by default availble to child
but child data not availble to parent.
and using child ref we can call both class data child and parent.
but using parent ref can call only to parent methods but can not call to child
method.

2-parent class ref can be used to hold child class object but by using that ref we
can call only parent class mem but
we can not call child specific methods.

3-child class ref can not be used to hold parent class object.

*MULTIPLE INHERITANCE [ not supported by java]:


-----------------------
> having more than one parent at the same level is called multiple inheritance.
Note:-any class can extends only one class at a time but can impl many interfaces.
java not support multiple inheritance.

Note:- but a interface can extends any no of interfaces at a time , so its provide
support for multiple inheritance through interface.

Ex: interface A{}


interface B{}

interface C extends A,B


{}

Note:-if our class does not extends any class then our class is direct child class
of object class.
if our class extends any class then its indirect child class of object , and
which forms multilevel inheritance.

Q-why java not support for multiple inheritance ?


ans:- There may be a chance of raising ambiguity problums.

** HAS-A : RELAITONSHIP: [reusability]


------------------------
>HAS-A , relation is also known as composition or aggregation.

ex: class Engine


{
}
class Car extends Engine
{
Engine e = new Engine();
}
here Car Has-A Engine reference.
* COMPOSITION:- [tight coupling]
---------------
>Composition: Stronger relationship, where the contained objects are dependent on
the container object's lifecycle.
If the container is destroyed, the contained objects are also destroyed.

> Without existing container object if there is no chance of existing contained


object then relationsip bw container object and
contained object is called composition, which is strong association.

* AGGREGATION :- [loose relationship]


----------------
>Aggregation: Weaker relationship, where the lifecycle of the objects is
independent. The contained objects can exist without the container object.
>without existing container object , if there is a chance of existing contained
object is called aggregation,
aggregation has weak association.

OR

** METHOD SIGNATURE:
--------------------
>consist of method name with argument types.
ex:
public void mehtodAdd(int i, float f)
{
}

Note:=> mehtodAdd(int i, float f) is a method signature.

Note:- in same class , we can not declare 2 method with same signature else get
compile time error.

**POLYMORPHISM :-
-----------------
>a method with same name with diff forms is concept of polymorphism.
ex: abs() method for int, long , float.

Note: - we can use Parent ref to hold any child objects.


we can use same List ref to hold ArrayList, LinkedList, Vector, Stack object.

ex: List l= new ArrayList();


List l= new LinkedList();
List l= new Vector();

*POLYMORPHISM : consist of-


----------------------------
1-Compiletime or static or earlybinding : [overloading + method hiding]
2-Runtime/dynamic/latebinding : [overriding]

OOPS : PILLARS-
---------------
1- inheritance is talks to reusability.
2- polymorphism talks to flexibility.
3- encapsulation talks to security.

** OVERLOADING :-(same method name but diff args)


-----------------
=> Overloading occurs when you define multiple methods with the same name but with
different parameters (either in number, type, or both) within the same class.
=> two methods are said to be overloaded if and only if both method have same name
but diff argument type.
=> overloading also considerd as "Compiletime or static or earlybinding"

CASE 1 : AUTOMATIC PROMOTION IN OVERLOADING:-


---------------------------------------------
> in overloading , if compiler is unable to find the method with exact match we
will not get any C.E. immediatally.
first compiler promotes args to next level and checks the matched is availble or
not...this process will be continued until all possible . this process is called
automatic promotion in overloading .

byte - > short -> int -> long -> float - double
|
char

Note:- in resolving overloaded, exact match will always get first priority,
in resolving overloaded, child class will get more prority than parent
class.

CASE 3: in general, VAR-ARGS- method will get less priority that is no other method
matched then only var-arg method get chance.
CASE 4: in overloading , runtime object will not play any role in overloading.

** OVERRIDING :
---------------
> Overriding occurs when a subclass provides its own implementation of a method
that is already defined in its superclass.
The method in the subclass must have the same name, return type, and parameter
list as the method in the superclass.
> Whatever parent has by default avaible to child through inheritance,
but if child is not satisfy then child allowed to re_define that parent class
method in child in its own way , this process is called overriding.

*overriding is also considerd as polymorphism or latebinding or late binding.


Nore:- in overriding runtime object will play the role and ref type is dummy.

*RULES FOR OVERRIDING:


----------------------
>method name and args(signatur) must be same.
>return type same and co-variant type are allowed.
CO-VARIANT:
ALLOWED PARENT => OBJECT NUMBER
| | |
CHILD => STRING INTEGER

NOTE ALLOWED PARENT => STRING DOUBLE


| | |
CHILD OBJECT INT

Note:- Co-variant return type concept is applicable only for object type not for
primitive.
Note:- private methods are not visible in child classes hence overriding concept is
not applicable for private method.
base on our requirment we can declare same parent private method in child it
is allowed , but it is not overriding.

Note:- parent class final method can not be override in child class.
Note:- parent class final method we can override as final in child class. we can
also override native methods in child.
Note:- we can override a non abstract method as abstract.
Note:- syncronized, strictfp will not has any restriction on overriding.
Note:- not allowed: final -->non final but non-final -> final is allowed.
native <====> non native, abstract <====> non abstract,
syncronized <====> non syncronized,
strictfp <====> non strictfp.

** CHECKED Vs Un-CHECKED EXCEPTION:


-------------------------------------
>the exception which are checked by compiler at runtime called checked exceptions.
ex: IOException and its child, SQLException, ServletException. are checked
exception.

>the exception which are not checked by compiler are called un-checked exceptions.
ex: RuntimeException and its child, + Error and its child are unchecked
exeception.
except / remaining are checked exception.

*OVERRIDING RULE:- while overriding if the child class method throws any checked
exception compulsory the parent class method should throw same checked exception.
else we get C.E
but
There is no restrictions on un-checked exceptions.

*OVERRIDING WITH RESPECT TO STATIC METHODS:


------------------------------------------
CASE 1: we can not overide a static method as non static.
same as
we can not override a non static method as static.

Note:- if we overriding static to static then its not overriding , its mehtod
hiding.
**METHOD HIDING:-re defining same parent class static method in child class.
-----------------
overriding hiding
-----------------------------------------------------------------------------------
------------
1.both non static 1.both static
2.take care by jvm 2.take care by compiler
3.runtime/dynamic/latebinding
3.compiletime/static/early binding.

-----------------------------------------------------------------------------------
------------

Note:- overriding concept is not applicable for variables.

OVERLOADING OVERRIDING
-----------------------------------------------------------------------------------
----------------------------------
1. method name must be same 1. Must be same
2. argument type diff 2. must be same.
3. method signature must be diff 3. must be same.
4. return type no restriction 4. same or co-variant.
5. private, static, final can not be overloaded. 5. also can not be
overriden.
6. no restriction on Access Modifiers 6. weak / reducing is not
allowed.
7. no restriction on throws clause 7. parent method should
throw same checked exception as child,
not restiction for un-
checked.
8.also called compiletime/static/early binding 8.also called
runtime/dynamic/late binding.
-----------------------------------------------------------------------------------
-------------------------

imp note:

1 : in overloading , we have check only same method name , and args diff ,
remaining things like return type extra not req.
but
2 : in overriding , we check everything like mehtod names, args, return type,
throws , modifiers.

**IMP:

Q-IN HOW MANY WAYS WE CAN CREATE OBJECT OR WAYS TO GET OBJECT ?
------------------------------------------------------------------
ANS:-
1- by using new operator:
ex: Test t = new Test();

2- by using newInstance() [reflection machanism]


ex: Test t = (Test)class.forName("Test").newInstance();

3- by using Clone()
ex: Test t1 = new Test();
Test t2 = (Test)t1.clone();

4- by using Factory methods:


ex: Runtime r = Runtime.getRuntime();
DateFormat df = DateFormat.getInstance();

5- by using Deserialization:
ex: FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Test t = (Test)ois.readObject();

**CONSTRUCTOR:
==============
>When we create an object some piece of code will be executed automatically to
perform initialization of an object
this piece of code is called "constructor".
>main objective of constructor is to perform initialization of object.

IMP NOTE:- whenever we r writing any arg const , its highly recommended to write no
arg const also.
ex:
class Contructor
{
int rollNo;
String name;
public String toString()
{
return "rollNo : "+rollNo +"\n" +"Name : "+name;
}
Contructor(int rollNo, String name)
{
this.rollNo=rollNo;
this.name=name;
}
public static void main(String[] args)
{
Contructor cn = new Contructor(1010,"BL");
Contructor cn2 = new Contructor(1020,"BL Gocher");
System.out.println(cn +"\n"+cn2);
//System.out.println(cn);
}
}

**CONSTRUCTORE Vs NON STATIC BLOCK:


----------------------------------
>both will be executed automatically for every object creation but first static
block executed then constructor.
Note: every time exe..st block and const.while object creation.

constructor:->main objective of const.. is to perform initialization of an object.


if we want to other activites then define instance block.
Note:-non static block and constructor both have diff purpose.
constructor can take args but instance block can not take args.
Note:-without creating obj ,non static block and default or param constructor will
not be executed.

*RULES TO WRITE CONSTRUCTOR:


============================
> name of const and class must be same.
> return type is not applicable for const. if we write by mistake then it considerd
as methods.
> allowed modifer on constructor is : public, default, private, protected.

Default Constructor:- if we r not writing at least one const then cmpiler will
generate default const.
if we r writing at least one const, then compiler not
generate default const.

Note: class contains either compiler generated const or programmer written const
but not both.

> D.C-always no args cosnt.


> access modifiers of D.C is same as class modifier
> D.C contains only one line "super();", note : super(); comes with args const
also

** SUPER() VS THIS():
======================
super() is used to call a parent class constructor from a subclass constructor.
this() is used to call another constructor within the same class.

>first line inside every const is super() or this() , if we r not writing anything
compiler will place super();
case1: super() or this() in first line.
case2: we can use super() or this() at a time, but not both.
case3: we can use only inside constructor , if out then error.

**SUPER(), THIS() SUPER, THIS


-------------------------------------------------------------------------
1.are const calls. 1. are kw
2.to invoke super and current class const directally 2. refers parent and class
class instance mem.
3.use inside only const as first line 3. use anywhere, except
satic area.

--------------------------------------------------------------------------

**OVERLOADING CONSTRUCTOR:
--------------------------
> a class can contain more than one constructor and all these const having same
name but diff args , called construcor overloading.

Note: overriding concept not used for constructor but constructor can be
overloaded.

Note: abstarct class contains const for child class object creation to perform
initialization of child object only.
Note: whenever we are creating child class obj then parent class const will be
executed.

Note:-recursive method call is always runtime exception where as recursive const


invocation is compile time error.

Nested call:- calling a method inside another method is called nested call.

Recursive call:- calling a method within same method is called recursive call.

IMP NOte:- whenever we r writing any arg const , its highly recommended to write no
arg const also

Note:- if parent class const throws some checked exception then compulsory child
class const should throw same checked excetion or its parent.

** SINGLETON CLASSES:-
=====================
> For any java class if we allow to create only one object , class is called
sigleton class.
ex: Runtime class
ActionServlet
ServletLocator
BusinessDelegate

ex :
Runtime r1=Runtime.getRuntime();
Runtime r2=Runtime.getRuntime();
Runtime r3=Runtime.getRuntime();

if(r1==r2) // true
if(r1==r3) // true

NEED OF SINGLETON CLASS:


------------------------
>if requirement is same then instead of creating a separate obj for every person,
we will create only one obj and we can share that object for every req person.
>singleton is created using private constructor and static variable and factory
method.

How to create Singleton class:


-----------------------------

class Test
{
private static Test t=null; // 1 static var
private Test() // 2 private constructor
{}
public static Test getTestObject()//3 factory method returning Test class
object if null.
{
if(t==null)
{
t=new Test();
}
return t;
}
}
class Singleton
{
public static void main(String[] args)
{
//Test t = new Test();
//Test t2= new Test();
System.out.println(Test.getTestObject().hashCode()); // 1579210
System.out.println(Test.getTestObject().hashCode()); // 1579210
}
}

Note:- we can also create xxxTon class by increasing static var and adding if
condition.

Q- if class is not final, how we can restrict or not allow to create child class
object ?
ans: by using private const.

class Parent{
private Parent(){
}
}

now we can not create child class for this class.

Note:- when creating child class object automatically parent class const will be
executed but parent object will not be created.
--------------------------------------------

** FACTORY METHOD:
------------------
>by using class name if we are calling a method and that method return same class
object , is called factory method.
ex: Test t=Test.getTest();
RunTime r = RunTime.getRuntime();
DateForamt df = DateFormat.getInstance();

-------------------------------------------------------

** STATIC CONTROL FLOW :-


--------------------------
ORDER:

1-identification of static members


2-execution of static variables assignment and static blocks from top to bottom.
3-execution of main method

FLOW WITH INHERITANCE:


1-identification of static member from parent to child.
2-execution of static var assignment and static blocks from parent to child.
3-execution of child main

or

1 P-SB (top to bottom)


2 C-SB
3 C-MAIN

Note:- whenever we r loading child class automatically parent class will be loaded
but
whenever we r loading parent class, child class do not loaded automatically.

-----------------------------

** STATIC BLOCK :-
------------------
> to perform any activity at the time of class loading , SB executed at the time of
class loading, from top to bottom.

Q-whithout using main() we can print some stmt to the console?


ans: using
1-static block or
2-static mathod called from static var

ex class google{
static
{
sop("hi its printint without main method.");
System.exit(0);
}

-------------------------

** INSTANCE CONTROL FLOW :-


---------------------------
-> whenever we are creating object the sequence of event will be performed:

1- identification of instance mem from top to bottom.


2- execution of instance var assignment and instance blocks from top to bottom
3- execution of constructor.

IMP NOTE:'
> static control flow is one time activity at the time of class loading.
but
> instance control flow is not one time, for every object creation it will be
executed.

Instance control flow in parent child:


---------------------------------------
1- identification of instance mem from parent to child
2- execution of instance var assignment and instance blocks only in Parent class.
3- execution of Parent class constructor.
4- execution of instance var assignment and instance blocks in child class.
5- execution of child class constructor.

------------------------------------------------------------

** TYPE CASTING :
------------------
>parent class ref can be used to hold child class object but by using that ref we
can not call child specific methods.

Note:- similarly we can use interface ref to hold impl class object.
ex: Runnable r = new Thread();

**COMPILE TIME CHECKING:-


-------------------------
RULE 1:
--------
>the type of d and c must have some relationship [either child to parent or vice
versa], else we get CE.
ex: valid
Object o =new String("jobs");
StringBuffer sb=(StringBuffer)o; // object o and StringBuffer has parent child
relationsip.

but invalid
String s = new String("delhi");
StringBuffer sb = (StringBuffer)s;

Rule 2:
-------
> "C" must be either same or derived type of "A" , else we get CE.

** RUNTIME CHECKING:
--------------------
>underlying(containing )object type of "D" must be either same or derived type "C".
else we get runtime exception saying:- ClassCastException.

** COUPLING :
-------------
the degree of dependency between component is called coupling.
if it is high , then its called tight coupling and
if it is low , then its called loose coupling.

** COHESION:
------------
>For every component we have to maintain a clear well defined functionality , said
to be high cohesion, its good programming.

You might also like