OOPS: Important Concepts
psmv = public static void main(String[] args){}sop,syso = System.out.println();
1. Class
a.Properties(fields) ,Methods
i.Static
ii. Non Static
b.access specifiers
c.this
d.Constructors,Method - Overloading and Overloading
2. Poly Morphism,Inheritance,Encapsulation
3. Concrete Class ,Interface ,Abstract Class
4. Final -variable ,method,class
5. Super - var ,method,class
6. StringBuffer
7. Collections – List ,Map,Set,Iterator
8. try…catch…finally
9.Overriding vs Overloading
10. Casting
11. Diamond Problem (Multiple inheritance)
12. Throw and Throws
13. Casting
14. Constructor rules
--------------------------------------------------------------------------
1. Class (types baseclass=parent class,super class and child class=derived class,subclass,implementing class)
a. Properties(fields) , Methods
>Static and Non Static
> Constructor cannot be static
>CLass A - HAS A - variable a and b
> Local Variable = Inside method or constructor,
> Instance variable = Private Varibale
>Class Variable =Static variable outside class
Class A{
static int a=10; //Any object can access and change , it is common !!
int b=30;
static void m1(){ //static method
Sop(a);
SOP(b); //Error- cannot access non static fields !!
}
void m2{Sop(a+b); } //Non Static method can access both variables
Psvm[String[] args]{
A.a =12; //Can Access static variables
A.b=12;// --Error Cannot access non static fields without Object
A.m1(); //Access static methods directly without creating instance
A.m2(); // --Error Cannot access non static methods directly without creating instance
A a=new A(); //Nonstatic needs instance
a.m1(); //instance – access both nonstatic and static methods
a.m2();
sop(A.a +A.b);//Static variable and Non static Variable
}
b. Access Modifiers (there is no Access specifiers in Java):
i. Private:Only members of the current class can access
ii. Protected: A protected variable is not visible outside the package
iii. Public: Anybody can access.
iv. Private Constructor = No object can be created for the class
v. Applicable for fields,methods and Constructors
c. This
Class A{
Int a=0;
A m1(int a){
this.a=a;//this – means current context of the class ie., Int a
this.m2();
return this; // Return A ie ., Current Class instance
}
void m2(){SOP("hi")};
}
2. Constructors and Method - Overriding and Overloading
Note :
1. Constructors= no return type.
2. Constructors= initialization of fields
3. Overloading- Same name but different arguments being passed
4. In A a=new B(); /a - can access all members of A and methods declared in A and defined or overriden in B
Note : By changing only the return type user cannot Overload in Java.
public class test1 {
public static void main(String [] args){
A a=new A(3); // calls 2nd constructor in A
B b=new B(); // obj “new B()” calls A() constructor
b.A(); //Method overriding - calls method A in B
b.A(3); //Inheritence -calls method -A(int a) in A
System.out.println(b.value);//Inheritence -CanAccess Base class fields
A a2=new B();// Calls Constructor A
a2.A(); //Call Overriding method A in B
}
}
class A{
String value="Hi";
A(){} //constructor- same name as class and no Return Type
A(int a) {}//constructor- same name as class with argument
void A(){} //method= has returntype
void A(int a){} //Method Overloading - same name different arguments
int A(){} //ERROR - Should have different argument ,just changing return type does not work }
class B extends A{
void A(){} //Overriding Method
void A(int a,int b){}; //Independent method
int A(){} ; //Error -shd be either overridden ie same return type as m1 in A or add argument to make independent
}
}
Output :
A const Overload
const empty //B b=new B(); --Calls parent Constructor : A(){System.out.println("const empty");}
B-m1,method Override
method A
BaseClass
Overriding
|
Overloading
|
Used in Inheritance
|
Used in same class
|
Overriding the method from the
parent class
|
Same method name but different
arguments in same class
|
Only 1
|
a)Method overloading
b)constructor overloading
|
Either arguments or both arguements and return type is accepted .Only Changing Return type not accepted
|
Only changing return type with same
arguments is not valid
|
3. Polymorphism, Inheritance, Encapsulation
1. All common members in Abstract Class : legs,meat,get_meat
2. Child Class = specific to itself : drools,setter,getter,eat / purs,setter,getter,eat
abstract class Animal{ //Abstract = restrict creation of object , avoid repetition
int legs; //legs = common to all animals
boolean meat=false;
Animal(int legs){ this.legs=legs; }
boolean get_meat(){ return meat; }
abstract void set_meat(); //
}
class dog extends Animal{ //Abstract uses 'extends' (Inheritance)
private Boolean drools; //drools= specific only to dog and cannot be accessed outside this class (Encapsulation)
dog(int legs){super(legs);} //Match Base Class Overloading constructor if it exists
dog(int legs,Boolean drools) {//Overloading Constructor
super(legs);
this.drools=drools;
}
public void set_drools(Boolean drools){} //Setter or Accessor -Encapsulation
public Boolean get_drools(){return drools;} // (Getter or mutator) - Encapsulation
void set_meat() {
super.meat=true; //This.meat=true or meat=true
}
}
class Cat extends Animal{ //Abstract uses 'extends' (Inheritance)
private Boolean purs; //Purs= specific to cat and cannot be accessed outside cat class (Encapsulation)
Cat(int legs) {super(legs); } //Mandatory to match super overloading constructor if it exists
public void set_purs(boolean purs){this.purs=purs;} //Setter or Accessor - Encapsulation
public String get_purs(){return purs;} //(Getter or mutator) -Encapsulation
void set_meat() { //abstraction
super.meat=true; //This.meat=true or meat=true;
}
}
public class test1 {
public static void main(String [] args){
ArrayList<Animal>a= new ArrayList<Animal>(); // Try using Arrays instead of arrayList
a.add(new dog(4,false)); //polymorphism - dog stored in animalList
a.add(new Cat(4)); //polymorphism - cat stored in animalList
for(Animal b:a){ //"enhanced for" - for (Iterator i=a.iterator();i.hasnext())
System.out.println("Number of tails"+b.legs); //Inheritance
b.set_meat(false);//abstraction -call se_meat in DOG
if(b instanceof dog){ //polymorphism
dog d=(dog)b;
d.set_drools("No");
System.out.println(d.get_drools()); //get_drool access private member -Access Encapsulation
b.set_meat(true);
System.out.println(d.get_meat()); //Inheritence -Base Class
}
}
}
}
4. Concrete Class, Interface , Abstract Class
Dog d=new Dog();
new Dog() is an Object
Dog d is a Variable
a) Super Class is Concrete Class :
Parent = Concrete Class
Main use :
1. Avoid repetition
2. Polymorphic loops
3. inheritance ie., (Super) child can use parents functions and variables
3. Overriding
Features:
a. Base Class = Makes sense to create Object instance for Parent class
b. Child Class=Satisfy IS-A (Cat-base, black cat-child / citizen-base , begger-base / etc.,)
d. SubClass can extend only one base class.
Class Dog{ //In Real world makes sense to create a Standalone Dog object
Void bark(){}
}
Class blind_dog extends Dog{ // Passes IS-ATest (blind dog is a Dog)
Void blind(){}
}
b) Super class is Interface
Super class is Interface
Main use :
a. Used for polymorphic arrays and lists ie., relief_fund[] r={new tiger() ,new farmer()};
b. Used as a template.
Properties
a. Child Class = Need not Satisfy IS-A (Any class can implement any interface)
b. Interface = Not real does not makes sense to create an object.
c. User can implement multiple interfaces unlike a class ie., class a implements A,B.C
d. Member variables declared should be "public static final"
d. Methods are only declared
d. Implementing class has to implement all method definitions
Interface relief_fund{ // relief for what ? without context does not make sense
Void food(); //Hence a stand alone reflief ject should not be created
}
class tiger implements relief_fund{ //there are tigers in real world
Void food(){sop(“skape goat”);} //food is same but implementation is different
}
class farmer implements relief_fund{ //there are farmer in real world
Void food(){sop(“subsidy”);
} //food is same but implementation is different
public static void main(String [] args){
ArrayList<relief_fund> r=new ArrayList<relief_fund>(); //Interface
r.add(new tiger()); //Interface are used to do this (add implementing class into itsown)
r.add(new farmer());//Interface are used to do this
Iterator i=r.iterator();//Iterator -Collection type =map,set,list
while(i.hasNext()){
relief_fund r1=(relief_fund) i.next(); //Cast
if(r1 instanceof tiger) //instanceof
((tiger)r1).food(); //doublecast
}
}
}
Output:skape goat
c) Abstract Class
(Parent = Abstract Class)
Main use :
a. Avoid repetition
b. used for polymorphic loops, arrays and lists.
c. Inheritance ie., (Super) child can use parents functions and variables
d. Satisfy IS-A (Animal-abstract,cow-child / furniture-abstract,chair-child /etc.,)
Properties :
a. Abstract Class (Base Class) = Not Real
b. Child Class = Satisy IS-A Rule
c. Abstract Class may or may not have abstract methods (method declaration)
d. If Abstract class has abstract method then that method should be defined in implementing class.
e. Make class Abstract if you do not want someone create object out of it.
f. Sub Class can extend only one base class.
g. Implementing class can override methods of base class
h, Even if there is 1 abstract method entire class =abstract
Abstract class Engineering_student
{
Abstract void dept(); //This implementation can be different
Void campus_interiew(){do something”} //Same for all depts
Void sports_facilities() {sop("cricket");} //same for all depts
}
Class EC_depth extends Engineering_student{
void dept(){Sop(“Electronics and Comm”);}
}
Class CS_depth extends Engineering_student{
void dept(){Sop(“Computer science”);}
}
psvm(String[] args){
EC_dept student1=new EC_dept();
CS_dept student2 =new CS_dept();
sop(student1.sportsfacilities()); //Student1 able to access methods in abstract method
Engineering_student[] s=new Engineering student[2];
s[0]=student1; //similar to interface , add subclasses into its own
s[1]=student2;
for( Engineering_student e: s) //enhanced for loop ie., (classname var : list_or_array)
if(e instance of CS_dept)
sop(((CS_dept)e).dept() );
}
Output :
Computer science
Interface
and Abstract class mainly used for polymorphic arrays ,array lists and
no
|
Interface
|
Abstract Class
|
1
|
Keyword
used “interface”
|
Keyword
used “abstract”
|
2
|
Only
method declaration
|
Can
have declaration as well as definition
|
3
|
No
Need
|
Only
Declared method should use abstract keyword
|
4
|
Only Polymorphism
|
Avoid
repetition
of common methods(Inheritence) and polymorphism
|
5
|
Can
only have ”static final” variable
|
Can
have all types of variables
|
6
|
Should
not create object
|
Same
|
7
|
Does
not exist in real world
|
Same
|
8
|
Interface
is a template
|
Not
a template
|
Note
: User cannot superclass an interface
SL
No
|
If
Superclass is Concrete Class
|
If
Superclass is Abstract Class
|
If
Class Implements Interface
|
Satisfy
IS-A
|
Same
|
No Need to satisfy IS-A
|
|
Use
“extends”
|
Use
“extends”
|
Use
“implements”
|
|
Only
1
|
Only
1
|
Any
no of interfaces can be used
|
|
NA
|
has
to define abstract methods
|
has
to define all methods
|
7.
Final
a.
Final variable
Final
int a=30;
Void
m1(){a=0; //error- cannot change
}
b.
Final method
Class
A{final void m1(){}}
c.
Final Class
Final
Class A{}
Class
B extends A{} //Error cannot extend final class
8.
Super = Constructor ,Method ,Var
Class
A{ int a;
void
m1(){SOP(“hi”);}
}
Class
B extends A {
B(){super();}
B(){super();}
void
m2(){
super.a=5;
super.m1();
}
super.a=5;
super.m1();
}
}
Output:
hi
9.
StringBuffer
StringBuffer
sBuff=new StringBuffer();
sBuff.append(“hi”);
SOP(sBuff);
a.
Immuttable
b.
Multi Thread friendly
output:hi
10.
Collection - ArrayList
ArrayList
l=new ArrayList();
l.add(0);
l.add(“hi”);
SOP(l);
Collections.sort(l);
output:0,hi
a.
Can store any datatype
b.
Better api (remove,add ie., better methods)
c.
Arraylist<dog> d=new
ArrayList<dog>();
- LinkedList similar to ArrayList requires more memory,slow to access specific elements but faster add and remove.
(http://stackoverflow.com/a/322722)
(http://stackoverflow.com/a/7507740)
Important methods of ArrayList:
E - Element of a particular datatype
e - Variable
T[]- Any DataType Array
- LinkedList similar to ArrayList requires more memory,slow to access specific elements but faster add and remove.
(http://stackoverflow.com/a/322722)
(http://stackoverflow.com/a/7507740)
Important methods of ArrayList:
E - Element of a particular datatype
e - Variable
T[]- Any DataType Array
- add(E e) //Insert any element into the arraylist
- add(int index, E element) //Insert any element into the arraylist @ a particular index
- addAll(int index, Collection<? extends E> c)
- clear() //remove all contents of arraylist
- contains(Object o) //validate if a particular object exists in the list , return boolean
- get(int index) //returns E
- indexOf(Object o) //return int
- isEmpty() //returns boolean
- remove(int index)
- remove(Object o)
- set(int index, E element)
- size() //int
- toArray() //returns an array of T[]
add(E e) ,add(int index, E element) ,addAll(),
clear(),remove(int index),remove(Object o)
contains(Object o),indexOf(Object o)
set(int index, E element),get(int index)
isEmpty() ,size()
toArray
clear(),remove(int index),remove(Object o)
contains(Object o),indexOf(Object o)
set(int index, E element),get(int index)
isEmpty() ,size()
toArray
HashMap
d=new HashMap();
d.put(“id”,”value”)
SOP(d.get(“id”));
output:value
12. Collection
– HashSet (Avoid repetitions)
HashSet s=new HashSet();
s.add(“hi”);
s.add(“hi”);
s.add(“hi”);
s.add(“hi”);
System.out.println(s.size());
output:1
output:1
13. Collection
– Iterator
ArrayList a = new
ArrayList();
a.add(1);
a.add("two");
Iterator i=a.iterator();
while(i.hasNext())
System.out.print(i.next().toString());
output:1,two.
14 try..catch..finally :
- Throwable is the parent.
- getmessage,printstacktrace methods are commonly used.
- Heriarachy is important
- finally executes no matter waht
try{
}catch
(FileNotFoundException e){
}catch
(ArrayIndexOutOfBoundsException e){
}catch
(ArrayIndexOutOfBoundsException | NullpointerException e){//Or operation
}finally{
//Always executes !!
}
15.
Casting - Mainly used with collection.iterator
Eg: In A a=new B(); //a - can access all members of A and methods declared in A and defined or overriden in B
Once Casted "a" From A to B ,it should be able to access all members from A and B.
public class test1 { Eg: In A a=new B(); //a - can access all members of A and methods declared in A and defined or overriden in B
Once Casted "a" From A to B ,it should be able to access all members from A and B.
public static void main(String [] args){
a A=new b(); //PolyMorphism
A.m1(); //Can Call Only m1
b B=(b)A;//Casting
B.m1(); //Call both m1() and m2()
B.m2(); //Call both m1() and m2()
}
}
class a {
void m1(){System.out.println("hi");}
}
class b extends a{ //b IS-A a
void m2(){}
}
16.Diamond Problem : Why we cannot
extend multiple class in a single subclass
class A{
int i;
void m1(){}
}
class B{
int i;
void m1(){}
}
class test extends A,B{ //Why multiple inheritance
is not allowed
void test(){
super.m1(); //which
one is called ?
super.i; //which one is called ?
}
}
17. Throw new and Throws
class A {
void m1() throws deepakException{
throw new deepakException("hi");
}
}
class deepakException extends Exception{
public deepakException(String str){}
}
18 . Constructor Rules :
In inheritance Parent Constructor executes always except :
- for static methods
- if overloaded constructor exists in parent
- If no constructor is defined - nothing is executed when Obj is created.
Dog= No Constructor
1. Animal has No constructor //no result
2. Animal has default constructor //Animal()
3. Animal has with parameters constructor // - Not allowed
Dog= default Constructor
1. Animal has No constructor //Only Dog()
2. Animal has default constructor // Animal() > Dog()
3. Animal with parameters constructor // Dog(){super(a);} //has to call parent constructor and pass argument
Dog= Constructor with Parameters
1. Animal has No constructor //Dog(parameter)
2. Animal has default constructor //Animal()>Dog(parameter)
3. Animal with parameters constructor // Dog(int a){super(a);}//has to call parent constructor and pass argument
Example 1: Child has no parameters in constructor
class Animal{ Animal (){sop("Animal");}}
class Dog extends Animal{Dog(){sop("Dog");}}
psym(String[] args){Dog d=new Dog();}
output:Animal Dog
Example 2: Child has parameters in constructor
class Animal{ Animal (){sop("Animal");}}
class Dog extends Animal{Dog(int b){sop(b);}}
psym(String[] args){Dog d=new Dog(5);}
output:Animal 5
Example 3:Parent Constructor accepts only parameters - then child has to implement the parent constructor .
class Animal{ Animal (int b){sop(b);}}
class Dog extends Animal{Dog(){super(5);}}
psym(String[] args){Dog d=new Dog(5);}
output:5
Example 4 : When no Constructor in Parent : Only child constructor executes
class Animal{ }
class Dog extends Animal{Dog(){sop("Dog");}}
psym(String[] args){Dog d=new Dog();}
output: Dog