Oops Concepts
Oops Concepts
1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation
Inheritance:-
1. The process of acquiring fields(variables) and methods(behaviors) from one class to another class
is called inheritance.
2. The main objective of inheritance is code extensibility whenever we are extending class
automatically the code is reused.
3. In inheritance one class giving the properties and behavior & another class is taking the
properties and behavior.
4. Inheritance is also known as is-a relationship. By using extends keyword we are achieving
inheritance concept.
5. extends keyword used to achieve inheritance & it is providing relationship between two classes
when you make relationship then able to reuse the code.
6. In java parent class is giving properties to child class and Child is acquiring properties from
Parent.
7. To reduce length of the code and redundancy of the code sun people introduced inheritance
concept.
1|P age
Note 1:-In java it is possible to create objects forboth parent and child classes.
1. If we are creating object for parent class it is possible to call only parent specific methods.
A a=new A();
a.m1();a.m2();
2. if we are creating object for child class it is possible to call parent specific and child specific.
B b=new B();
b.m1();b.m2(); b.m3();b.m4();
C c=new C();
c.m1(); c.m2(); c.m3();c.m4();c.m5();c.m6();
Types of inheritance :-
There are five types of inheritance in java
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid Inheritance
Single inheritance:-
One class has one and only one direct super class is called single inheritance.
In the absence of any other explicit super class, every class is implicitly a subclass of Object class.
Example:-
class Parent
{ void property(){System.out.println("money");}
};
class Child extends Parent
{ void m1() { System.out.println("m1 method"); }
public static void main(String[] args)
{ Child c = new Child();
c.property(); //parent class method executed
c.m1(); //child class method executed
}
};
Multilevel inheritance:-
One Sub class is extending Parent class then that sub class will become Parent class of next
extended class this flow is called multilevel inheritance.
2|P age
Class B extends A ===> class B acquiring properties of A class
Class C extends B ===> class C acquiring properties of B class
[indirectly class C using properties of A & B classes]
Example:-
class A
{ void m1(){System.out.println("m1 method");}
};
class B extends A
{ void m2(){System.out.println("m2 method");}
};
class C extends B
{ void m3(){System.out.println("m3 method");}
public static void main(String[] args)
{ A a = new A(); a.m1();
B b = new B(); b.m1(); b.m2();;
Example:-
class A
{ void m1(){System.out.println("A class");}
};
class B extends A
{ void m2(){System.out.println("B class");}
};
class C extends A
{ void m2(){System.out.println("C class");}
};
class Test
{ public static void main(String[] args)
{ B b= new B();
b.m1(); b.m2();
C c = new C();
c.m1(); c.m2();
}
};
Multiple inheritance:-
One sub class is extending more than one super class is called Multiple inheritance and java not
3|P age
supporting multiple inheritance because it is creating ambiguity problems (confusion state) .
Java not supporting multiple inheritance hence in java one class able to extends only one class at
a time but it is not possible to extends more than one class.
Class A extends B ===>valid
Class A extends B ,C ===>invalid
Example:-
class A
{ void money(){System.out.println("A class money");}
};
class B
{ void money(){System.out.println("B class money");}
};
class C extends A,B
{ public static void main(String[] args)
{ C c = new C();
c.money(); //which method executed A--->money() or B--->money
}
};
Hybrid inheritance:-
Hybrid is combination of hierarchical & multiple inheritance .
Java is not supporting hybrid inheritance because multiple inheritance(not supported by
java) is included in hybrid inheritance.
Preventing inheritance:-
You can prevent sub class creation by using final keyword in the parent class declaration.
final class Parent //for this class child class creation not possible because it is final.
{
};
class Child extends Parent
{
};
4|P age
5) public java.lang.String toString();
6) public final native void notify();
7) public final native void notifyAll();
8) public final native void wait(long) throws java.lang.InterruptedException;
9) public final void wait(long, int) throws java.lang.InterruptedException;
10) public final void wait() throws java.lang.InterruptedException;
11. protected void finalize() throws java.lang.Throwable;}
Example :-
In java if we are extending java class that extended class will become Parent class , if we are not
extending Object class will become Parent class.
In below example
A class Parent is----- > Object
B class Parent is----- >A
C class Parent is----- >B
class A
{ void m1(){} };
class B extends A
{ void m2(){} };
class C extends B
{ void m3(){} };
In above example A class Parent is Object class
Object class contains------- >11 methods
A class contains------------- >12 methods
B class contains------------- >13 methods
C class contains------------- >14 methods
Instanceof operator:-
It is used check the type of the object and return Boolean value as a return value.
Syntax:- reference-variable instanceof class-name;
Example:- Test t=new Test();
t instanceof Test
Whenever we are using instanceof operator the reference variable and class-name must have
some relationship either [parent to child] or [child-parent] otherwise compiler generates error
message “inconvertible types”
If the relationship is
o Child – parent returns true
o Parent - child returns false
Example :-
class Animal{ };
class Dog extends Animal{ };
class Test
{ public static void main(String[] args)
{ //syntax: (ref-ver instanceof class-name);
String str="ratan";
Animal a = new Animal();
Dog d = new Dog();
5|P age
Object o = new Object();
System.out.println(a instanceof Object); //true [child-parent]
System.out.println(d instanceof Animal); //true [child-parent]
System.out.println(str instanceof Object); //true [child-parent]
System.out.println(o instanceof Animal); //false [parent-child]
System.out.println(a instanceof Dog); //false [parent-child]
//no relationship compilation error :inconvertible types
//System.out.println(str instanceof Animal);
}
}
Association:-
Class A uses class B
When one object wants another object to perform services for it.
Relationship between teacher and student, number of students associated with one teacher or
one student can associate with number of teachers. But there is no ownership and both objects
have their own life cycles.
Example-1:-
class Student
{ int sid;
String sname;
Student(int sid,String sname) //local variables
{ //conversion
this.sid =sid;
this.sname=sname;
}
void disp()
{ System.out.println("***student details***");
System.out.println("student name--->"+sname);
System.out.println("student name--->"+sid);
}
};
Class RatanTeacher //teacher uses Student class "association"
{ public static void main(String[] args)
{ Student s1 = new Student(111,"ratan");
Student s2 = new Student(222,"anu");
s1.disp(); s2.disp();
}
};
Example-2:-
class Ratan
{ void disp(){System.out.println("ratan : corejava");}
};
class Anu
{ void disp(){System.out.println("anu : advjava");}
};
class Sravya
{ void disp(){System.out.println("Sravya : ocjp");}
};
6|P age
class Student //student uses different teachers "association"
{ public static void main(String[] args)
{ Ratan r = new Ratan(); r.disp();
Anu a = new Anu(); a.disp();
Sravya d = new Sravya(); d.disp();
}
};
Aggregation:-
Class A has instance of class B.
Class A can exists without presence of class B . a university can exists without chancellor.
Take the relationship between teacher and department. A teacher may belongs to multiple
departments hence teacher is a part of multiple departments but if we delete department object
teacher object will not destroy.
Example -1:-
//Teacher.java
class Teacher
{ //instance variables
String tname,sub;
Teacher(String tname,String sub)//local variables
{ //conversion
this.tname=tname; this.sub=sub;
}
};
//Department.java:-
class Department //if we delete department teacher can exists is called aggregation
{ //instance variables
int did;
Teacher t;
Department(int did ,Teacher t) //local variables
{ //conversion
this.did = did; this.t = t;
}
void disp()
{ System.out.println("Department id :--->"+did);
System.out.println("Teacher details :--->"+t.tname+"---"+t.sub);
}
}
}
Example -2:
Address.java
class Address
7|P age
{ //instance variables
String country, state;
int hno;
Address(String country,String state,int hno)//local variables
{//passing local variable values to instance variables (conversion)
this.country = country; this.state= state; this.hno = hno;
}
};
Heroin.java:
class Heroin
{ //instance varaibles
String hname; int hage;
Address addr;//reference of address class [address class can exists without Heroin class]
Heroin(String hname,int hage,Address addr)//localvariables
{ //conversion of local variables to instance variables
this.hname = hname; this.hage = hage; this.addr = addr;
}
void display()
{ System.out.println("*********heroin details******");
System.out.println("heroin name-->"+hname);
System.out.println("heroin age-->"+hage);
//printing address values
System.out.println("heroin address-->"+addr.country+" "+addr.state+" "+addr.hno)
}
public static void main(String[] args)
{ //object creation of Address class
8|P age
Example-3:-Test1.java:- class Test1
{ //instance variables
int a;int b;
Test1(int a,int b)
{ this.a=a;this.b=b;
}
};
9|P age
Test2.java:-
class Test2
{//instance variables
boolean b1;boolean b2;
Test2(boolean b1,boolean b2)
{ this.b1=b1;this.b2=b2;
}
};
Test3.java:-
class Test3
{ //instance variables
MainTest.java:-
class Test
{ //instance variables
Test1 t1;
Test2 t2;
Test3 t3;
Test(Test1 t1 ,Test2 t2,Test3 t3)//constructor [local variables]
{ //conversion of local-instance
this.t1 = t1;
this.t2 = t2;
this.t3 = t3;
}
void display()
{ System.out.println(“Test1 object values:-”+t1.a+"-----"+t1.b);
System.out.println(“Test2 object values:-”+t2.b1+"-----"+t2.b2);
System.out.println(“Test3 object values:-”+t3.ch1+"-----"+t3.ch2);
}
public static void main(String[] args)
{ Test1 t = new Test1(10,20);
Super keyword:-
10 | P a g e
Super keyword is holding super class object. And it is representing
1. Super class variables
2. Super class methods
{ //instance variables
int a=100;
int b=200;
void m1(int a,int b) //local variables
{ System.out.println(a+b); //local variables addition
System.out.println(this.a+this.b); //current class variables addition
System.out.println(super.a+super.b); //super class variables addition
In above example sub class and super class having same variable names hence to represent.
a. sub class variables use this keyword.
b. Super class variables use super keyword.
11 | P a g e
Superkeyword requeired:-
class Parent
{ void m1(int a){ System.out.println("parent m1()-->"+a); }
};
class Child extends Parent
{ void m1(int a){ System.out.println("child m1()-->"+a); }
void m2()
{ this.m1(10); //child class m1(int) method calling
System.out.println("child m2()");
In above exmple super class and sub class contains methods with same names( m1() ) at that situation
to represent.
a. Super class methods use super keyword.
b. Sub clss methods use this keyword.
12 | P a g e
};
class Child extends Parent{
Child()
{ this(10); //current class 1-arg constructor calling
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ super(); //super class 0-arg constructor calling
Example-3:-
Inside the constructor this keyword must be first statement and super keyword must be first statement
hence inside the constructor it is possible to use either this keyword or super keyword but both at a time
not possible.
No compilation Error:-
Child()
{ this(10);//current class 1-arg constructor calling(must be first line)
System.out.println("Child 0-arg constructor");
}
Compilation Error:-
Child()
{ this(10);//current class 1-arg constructor calling
super();//super class 0-arg constructor calling
System.out.println("Child 0-arg constructor");
}
Example-4:-
1. Inside the constructor (weather it is default or parameterized) if we are not declaring super or
this keyword at that situation compiler generate super() keyword at first line of the constructor.
2. If we are declaring t lest one constructor compiler is not responsible to generate super()
keyword.
3. The compiler generated super keyword is always 0-argument constructor calling.
class Parent
{ Parent() { System.out.println("parent 0-arg constructor"); }
};
class Child extends Parent
{
Child()
{ //super(); generated by compiler at compilation time
System.out.println("Child 0-arg constructor");
}
public static void main(String[] args)
{ Child c = new Child();
13 | P a g e
}
};
D:\>java Child
parent 0-arg constructor
Child 0-arg constructor
Example-5:-
In below example parent class default constructor is executed that is provided by compiler.
class Parent
{ //default constructor Parent() { } generated by compiler at compilation time
};
Example-6:-
By using below example we are assigning values to instance variable at the time of object creation eith
the help of parameterized constructor.
class Parent
{ int a; //instance variable
Parent(int a)//local variable
{ //conversion of local variable to instance variable
this.a=a;
}
};
class Child extends Parent
{ boolean x; //instance variable
Child(boolean x) //local variable
{ super(10); //super class constructor calling
this.x =x ; //conversion of local variable to instance variable
(passing local variable value to instance variable)
}
void display()
14 | P a g e
{ System.out.println(a);
System.out.println(x);
}
public static void main(String[] args)
{ Child c = new Child(true);
c.display();
}
};
D:\>java Child
parent 0-arg cons
child 1-arg cons
Child 0-arg constructor
Example-9:-
Inside the constructor either it is zero argument or parameterized if we are not providing super
or this keyword at that situation compiler generate super keyword at first line of constructor.
class Parent
{ Parent() { System.out.println("parent 0-arg cons"); }
};
class Child extends Parent
{ Child()
{ //super(); generated by compiler
System.out.println("Child 0-arg constructor");
}
Child(int a)
{ //super(); generated by compiler
System.out.println("child 1-arg cons");
}
public static void main(String[] args)
{
Child c = new Child();
Child c1 = new Child(10);
}
};
D:\>java Child
parent 0-arg cons
Child 0-arg constructor
15 | P a g e
parent 0-arg cons
child 1-arg cons
Example-10:-
In below compiler generate default constructor and inside that default constructor super keyword is
generated by compiler.
Application code before compilation:- ( .java ) class Parent
class Parent { Parent(){System.out.println("parent 0-
{ arg cons"); }
Parent(){ System.out.println("pa };
rent 0-arg cons");} class Child extends Parent
}; { /* below code is generated by compiler
class Child extends Parent Child()
{ public static void main(String[] args) { super();
{ Child c = new Child(); }*/
} public static void main(String[] args)
}; { Child c = new Child();
}
};
Application code after compilation:- ( .class )
Example-11:-
In below example inside the 1-argument constructor compiler generate super( ) keyword hence it is
executing super class(Object)0-argument constructor is executed.
Application code before compilation:- ( .java ) Application code after compilation:- ( .class )
class Test (Object class 0-arg constructor executed)
{ class Test extends Object
Test(int a){ { Test(int a)
System.out.println("Test 1-arg cons"); {
} super(); //generated by compiler
public static void main(String[] args) System.out.println("Test 1-arg cons");
{ }
Test t = new Test(10); public static void main(String[] args)
} { Test t = new Test(10);
}; }
};
Note 1:- in java if we are extending class that extended class will become super class
16 | P a g e
Ex :- class B{ }
class A extends B //B class is Parent of A class
{ }
Note 2 :- in java if we are not extending any class then Object class will become parent of that class.
Ex :- class A { } //in this Object class is Parent of A class
Note:-
1. Every class in the java programming either directly or indirectly child class of Object.
2. Root class for all java classes is Object class.
3. The object class present in java.lang package
Example : assignment
class GrandParent
{ int c;
GrandParent(int c)
{ this.c=c;
}
};
class Parent extends GrandParent
{ int b;
Parent(int b,int c)
{ super(c);
this.b=b;
}
};
class Child extends Parent
{ int a;
Child(int a,int b,int c)
{ super(b,c);
this.a=a;
}
void disp()
{ System.out.println("child class ="+a);
System.out.println("parent class ="+b);
System.out.println("grandparent class ="+c);
}
public static void main(String[] args)
{ new Child(10,20,30).disp();
}
};
17 | P a g e
class Parent
{ {System.out.println("parent instance block");}//instance block
};
class Child extends Parent
{
{ System.out.println("Child instance block"); } //instance block
Child() { System.out.println("chld 0-arg cons"); } //constructor
public static void main(String[]
args){Child c = new Child();
}
};
Example-2:-
In below example just before child class instance blocks first parent class instance blocks are executed.
class Parent
{ {System.out.println("parent instance block");}//instance block
Parent(){System.out.println("parent cons");}//constructor
};
class Child extends Parent
{ {System.out.println("Child instance block");}//instance block
Child()
{ //super(); generated by compiler
System.out.println("chld 0-arg cons");}
}
Child(int a)
{ //super(); generated by compiler
System.out.println("chld 1-arg cons");
}
public static void main(String[] args)
{ Child c = new Child();
18 | P a g e
{
{System.out.println("parent class ins block");}
Parent()
{ System.out.println("parent class 0-arg cons");
}
};
class Child extends Parent
{
{System.out.println("Child class ins block");}
Child()
{ //super(); generated by compiler
System.out.println("child class 0-arg cons");
}
public static void main(String[] args)
{ new Child();
}
};
E:\>java Child
parent class static block
child class static block
parent class ins block
parent class 0-arg cons
Child class ins block
child class 0-arg cons
parent class ins block
parent class 0-arg cons
Child class ins block
child class 0-arg cons
Parent class static block:-
Example-1:-
In parent and child relationship first parent class static blocks are executed only one time then
child class static blocks are executed only one time because static blocks are executed with
respect to .class loading.
19 | P a g e
class Parent
{ static{System.out.println("parent static block");}//static block
};
class Child extends Parent
{
static{System.out.println("child static block");} //static block
public static void main(String[] args)
{
}
};
class Parent
{ Parent(){System.out.println("parent 0-arg cons");}
{System.out.println("parent class instance block");}
static{System.out.println("parent class static block");}
};
class Child extends Parent
{ {System.out.println("child class instance block");}
Child()
{ //super(); generated by compiler
System.out.println("child class 0-arg cons");
}
static {System.out.println("child class static block");}
public static void main(String[] args)
{ new Child();
}
};
Example-2:-
Note 1:-instanceblocks execution depends on number of object creations but not number of
constructor executions. If we are creating 10 objects 10 times constructors are executed just
before constructor execution 10 times instance blocks are executed.
20 | P a g e
Note 2:-Static blocks execution depends on .class file loading hence the static blocks are
executed only one time for single class.
class Parent
{ static {System.out.println("parent static block");}//static block
{System.out.println("parent instance block");}//instance block
Parent(){System.out.println("parent 0-arg cons");}//constructor
};
class Child extends Parent
{ static {System.out.println("Child static block");}//static block
{System.out.println("child instance block");} //instance block
Child()
{ //super(); generated by compiler
System.out.println("Child 0-arg cons");}
Child(int a){
this(10,20);//current class 2-argument constructor calling
System.out.println("Child 1-arg cons");}
Child(int a,int b)
{ //super(); generated by compiler
System.out.println("Child 2-arg cons");
}
public static void main(String[] args)
{ Parent p = new Parent(); //creates object of Parent class
Child c = new Child(); //creates object of Child class
Child c1 = new Child(100);//creates object of child class
}
};
D:\>java Child
parent static block
Child static block
parent instance block
parent 0-arg cons
parent instance block
parent 0-arg cons
child instance block
Child 0-arg cons
parent instance block
parent 0-arg cons
child instance block
Child 2-arg cons
Child 1-arg cons
21 | P a g e
Polymorphism:-
One thing can exhibits more than one form is called polymorphism.
Polymorphism shows some functionality(method name same) with different logics execution.
The ability to appear in more forms is called polymorphism.
Polymorphism is a Greek word poly means many and morphism means forms.
There are two types of polymorphism in java
1) Compile time polymorphism / static binding / early binding
[method execution decided at compilation time]
Example :- method overloading.
2) Runtime polymorphism /dynamic binding /late binding.
[Method execution decided at runtime].
Example :- method overriding.
Method overloading:-
Example:-
class Test
{ //below three methods are overloaded methods.
void m1(char ch) {System.out.println(" char-arg constructor "); }
void m1(int i) {System.out.println("int-arg constructor "); }
void m1(int i,int j) {System.out.println(i+j); }
public static void main(String[] args)
{Test t=new Test();
//three methods execution decided at compilation time
t.m1('a');t.m1(10);t.m1(10,20);
}
}
Example :- overloaded methods vs. all data types
22 | P a g e
class Test
{ void m1(byte a) { System.out.println("Byte value-->"+a); }
void m1(short a) { System.out.println("short value-->"+a); }
void m1(int a) { System.out.println("int value-->"+a); }
void m1(long a) { System.out.println("long value is-->"+a); }
void m1(float f) { System.out.println("float value is-->"+f); }
void m1(double d) { System.out.println("double value is-->"+d); }
void m1(char ch) { System.out.println("character value is-->"+ch); }
void m1(boolean b) { System.out.println("boolean value is-->"+b); }
void sum(int a,int b)
{ System.out.println("int arguments method");
System.out.println(a+b);
}
void sum(long a,long b)
{ System.out.println("long arguments method");
System.out.println(a+b);
}
public static void main(String[] args)
{
Test t=new Test();
t.m1((byte)10); t.m1((short)20); t.m1(30); t.m1(40);
t.m1(10.6f); t.m1(20.5); t.m1('a'); t.m1(true);
t.sum(10,20);
t.sum(100L,200L);
}
}
Constructor Overloading:-
The class contains more than one constructors with same name but different arguments is called
constructor overloading.
class Test
{ //overloaded constructors
Test() { System.out.println("0-arg constructor"); }
Test(int i) { System.out.println("int argument constructor"); }
Test(char ch,int i){ System.out.println(ch+"-----"+i); }
public static void main(String[] args)
{ Test t1=new Test(); //zero argument constructor executed.
Test t2=new Test(10); // one argument constructor executed.
Test t3=new Test('a',100);//two argument constructor executed.
}
}
Operator overloading:-
One operator with different behavior is called Operator overloading .
Java is not supporting operator overloading but only one overloaded in java language is ‘+’.
o If both operands are integer + perform addition.
o If at least one operand is String then + perform concatenation.
Example:-
class Test
23 | P a g e
{ public static void main(String[] args)
{ int a=10;
int b=20;
System.out.println(a+b); //30 [addition]
System.out.println(a+"ratan"); //10Ratan [concatenation]
}
}
Runtime polymorphism [Method Overriding]:-
1) If we want to achieve method overriding we need two class with parent and child
relationship.
2) The parent class method contains some implementation (logics).
a. If child is satisfied use parent class method.
b. If the child class not satisfied (required own implementation) then override the
method in Child class.
3) A subclass has the same method as declared in the super class it is known as method
overriding.
The parent class method is called ===> overridden method
The child class method is called ===> overriding method
While overriding methods must fallow these rules:-
1) While overriding child class method signature & parent class method signatures must be same
otherwise we are getting compilation error.
2) The return types of overridden method & overriding method must be same.
3) While overriding the methods it is possible to maintains same level permission or increasing
order but not decreasing order, if you are trying to reduce the permission compiler generates
error message “attempting to assign weaker access privileges ”.
4) You are unable to override final methods. (Final methods are preventing overriding).
5) While overriding check the covariant-return types.
6) Static methods are bounded with class hence we are unable to override static methods.
24 | P a g e
7) It is not possible to override private methods because these methods are specific to class.
If a subclass defines a static method with the same signature as a static method in the superclass, then the
method in the subclass hides the one in the superclass.
class Animal
{ void instanceMethod(){System.out.println("instance method in Animal");}
static void staticMethod(){System.out.println("static method in Animal");}
};
class Dog extends Animal
{ void instanceMethod(){System.out.println("instance method in Dog");}//overriding
static void staticMethod(){System.out.println("static method in Dog");}//hiding
public static void main(String[ ] args)
{ Animal a = new Dog();
a.instanceMethod();
a.staticMethod(); // [or] Animal.instanceMethod();
}
};
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the
superclass or the subclass.
The Cat class overrides the instance method in Animal and hides the static method in Animal.
The main method in this class creates an instance of Cat and invokestestClassMethod() on the class
and testInstanceMethod() on the instance.
25 | P a g e
}
};
Covariant return types :-
Example 1:-
in below example overriding is not possible because overridden method return type &
overriding method return types are not matched.
class Parent
{ void m1(){}
};
class Child extends Parent
{int m1(){}
};
Compilation error:- m1() in Child cannot override m1() in Parent
return type int is not compatible with void
Example-2:-
1) Before java 5 version it is not possible to override the methods by changing it’s return types .
2) From java5 versions onwardsjava supports support covariant return types it means while
overriding it is possible to change the return types of parent class method(overridden method)
&child class method(Overriding).
3) The return type of overriding method is must be sub-type of overridden method return type this
is called covariant return types.
class Animal
{ void m2(){System.out.println("Animal class m2() method");}
Animal m1()
{ return new Animal();
}
}
class Dog extends Animal
{ Dog m1()
{ return new Dog();
}
public static void main(String[] args)
{ Dog d = new Dog(); d.m2();
Dog d1 = d.m1(); //[d.m1() returns Dog object]
d1.m2();
Animal a = new Animal();
a.m2();
Animal a1 = a.m1(); // [a.m1() returns Animal object]
a1.m2();
}
};
Type-casting:-
The process of converting data one type to another type is called type casting.
There are two types of type casting
1. Implicit typecasting /widening/up casting
2. Explicit type-casting (narrowing)/do
26 | P a g e
Type casting chart:-
Up-casting :-
Byte short
Int float double
char
down-casting:-
Note :- Parent class reference variable is able to hold child class object but Child class reference
variable is unable to hold parent class object.
class Parent
{ };
class Child extends Parent
{ };
27 | P a g e
long l = f;
System.out.println(l); compilation error:possible loss of precision (memory
representation different) */
//explicit-typecasting (down-casting)
// converted-type-name var-name = (converted-type-name)conversion-var-type;
int a1=120;
byte b1 =(byte)a1;
System.out.println(b1);
int a2=130;
byte b2 =(byte)a2;
System.out.println(b2);
float ff=10.5f;
int x = (int)ff;
System.out.println(x);
Parent p = new Child();
//target-type variable-name=(target-type)source-type;
Child c1 =(Child)p;
Parent p = new Child();
Child c1 = (Child)p;
}
}
Example-2:-
In java parent class reference variable is able to hold Child class object but Child class reference
variable unable to hold Parent class object.
o Parent p = new Child();---- >valid
o Child c = new Parent();----->invalid
class Parent
{ void m1(){System.out.println("parent m1 method");} //overridden method
}
class Child extends Parent
{ void m1(){System.out.println("child m1 method");} //override method
void m2(){System.out.println("child m2 method");} //direct method of child class
public static void main(String[] args)
{
//parent class is able to hold child class object
Parent p1 = new Child(); //creates object of Child class
p1.m1(); //child m1() will be executed
//p1.m2(); Compilation error we are unable to call m2() method
Child c1 =(Child)p1; //type casting parent reference variable to child object.
c1.m1();
c1.m2();
}
};
In above example parent class is able to hold child class object but when you call p.m1();
method compiler is checking m1() method in parent class at compilation time. But at runtime
child object is created hence Child method will be executed.
Based on above point decide in above method execution decided at runtime hence it is a runtime
28 | P a g e
polymorphism.
When you call p.m2 (); compileris checking m2 () method in parent class since not there so
compiler generate error message. Finally it is not possible to call child class m2 () by using parent
reference variable even thought child object is created.
Based on above point we can say by using parent reference it is possible to call only overriding
methods (m1 () ) of child class but it is not possible to call direct method(m2() ) of child class.
To overcome above limitation to call child class method perform typecasting.
Example :- importance of converting parent class reference variable into child class object
//let assume predefined class
class ActionForm
{ void xxx(){} //predefined method
void yyy(){} //predefined method
};
class LoginForm extends ActionForm //assume to create LoginForm our class must extends ActonForm
29 | P a g e
}
};
Example :-
class Animal
{void eat(){System.out.println("animal eat");}
};
class Dog extends Animal
{void eat(){System.out.println("Dog eat");}
};
30 | P a g e
class Cat extends Animal
{ void eat(){System.out.println("cat eat");}
};
class Test
{ public static void main(String[] args)
{ Animal a1,a2;
31 | P a g e
System.out.println("a vlues is :--->"+p.a);//100
Child c = (Child)p;
System.out.println("a vlues is :--->"+c.a);//1000
}
};
Method overloading:-
toString():-
toString() method present in Object and it is printing String representation of Object.
toString() method return type is String object it means toString() method is returning
32 | P a g e
String object.
The toString() method is overridden some classes check the below implementation.
o In String class toString() is overridden to return content of String object.
o In StingBuffer class toString() is overridden to returns content of StringBuffer
class.
o In Wrapper classes(Integer,Byte,Character…etc) toString is overridden to returns
content of Wrapper classes.
internal implementation:-
class Object
{ public String toString()
{ return getClass().getName() + '@' + Integer.toHexString(hashCode());
}
};
Example:-
Note :- whenever you are printing reference variable internally toString() method is called.
Test t = new Test(); //creates object of Test class reference variable is “t”
//the below two lines are same.
System.out.println(t);
System.out.println(t.toString());
class Test
{ public static void main(String[] args)
{ Test t = new Test();
System.out.println(t);
System.out.println(t.toString()); // [Object class toString() executed]
}
};
Example -2:-
toString() method present in Object class but in our Test class we are overriding toString()
method hence our class toString() method is executed.
class Test
{ //overriding toString() method
public String toString()
{ return "ratansoft";
}
public static void main(String[] args)
{ Test t = new Test();
//below two lines are same
System.out.println(t); //Test class toString() executed
33 | P a g e
{ //instance variables
String sname;
int sid;
Student(String sname,int sid) //local variables
{ //conversion
this.sname = sname;
this.sid = sid;
}
public String toString() //overriding toString() method
{ return "student name:-->"+sname+" student id:-->"+sid;
}
};
class TestDemo
{ public static void main(String[] args)
{ Student s1 = new Student("ratan",111);
//below two lines are same
System.out.println(s1); //student class toString() executed
System.out.println(s1.toString()); //student class toString() executed
34 | P a g e
int eid ;
double esal;
Employee(String ename,int eid,double esal) //local variables
{ //conversion of local variables to instance variables
this.ename = ename;
this.eid = eid;
this.esal = esal;
}
public static void main(String[] args)
{ Employee e1 = new Employee("ratan",111,60000);
//whenever we are printing reference variables internally it calls toString() method
System.out.println(e1); //e1.toString() [our class toString() executed output printed]
}
};
D:\morn11>java Employee
Employee@530daa
In above example Employee class is not overriding toString() method so parent class(Object)
toString() method will be executed it returns hash code of the object.
35 | P a g e
};
In above example when you print reference variables it is executing toString() hence Employee
values will be printed.
Final modifier:-
1) Final is the modifier applicable for classes, methods and variables (for all instance,
Static and local variables).
Case 1:-
1) if a class is declared as final, then we cannot inherit that class it means we cannot create child
class for that final class.
2) Every method present inside a final class is always final but every variable present inside the
final class not be final variable.
Example :-
final class Parent //parent is final class child class creation not possible
{ };
class Child extends Parent //compilation error
{ };
Example :-
Note :- Every method present inside a final class is always final but every variable present inside the
final class not be final variable.
final class Test
{ int a=10; //not a final variable
void m1() //final method
Compilation Error :- cannot assign a value to final variable a
Example :-
class Parent
{ void m1(){}
};
class Child extends Parent
{ int m1(){}
};
D:\morn11>javac Test.java
m1() in Child cannot override m1() in Parent
return type int is not compatible with void
36 | P a g e
};
Abstract class:-
Abstract class is a javaclass which contains at least one abstract method(wrong definition).
If any abstract method inside the class that class must be abstract.
37 | P a g e
Example 1:-
class Test //abstract class
{
void m1(){}//normal methodvoid m2(){}//normal methodvoid m3();//abstract method
};
Example-2:-
class Test //abstract class
{
abstract void m1();//abstract method abstract void m2();//abstract method abstractvoid
m3();//abstract method
};
Abstract modifier:-
Abstract modifier is applicable for methods and classes but not for variables.
To represent particular class is abstract class and particular method is abstract method to the
compiler use abstract modifier.
The abstract class contains declaration of methods it says abstract class partially implement
class hence for partially implemented classes object creation is not possible. If we are trying to
create object of abstract class compiler generate error message “class is abstract con not be
instantiated”
Example -1:-
Abstract classes are partially implemented classes hence object creation is not possible.
For the abstract classes object creation not possible, if you are trying to create object compiler will
generate error message.
}
};
Compilation error:- Test is abstract; cannot be instantiated
Test t = new Test();
Example-2 :-
Abstract class contains abstract methods for that abstract methods provide the
implementation in child classes.
Provide the implementations is nothing but override the methods in child classes.
The abstract class contains declarations but for that declarations implementation is present in
child classes.
38 | P a g e
abstract class Test
{ abstract void m1();
abstract void m2();
abstract void m3();
void m4(){System.out.println("m4 method");}
};
class Test1 extends Test
{ void m1(){System.out.println("m1 method");}
void m2(){System.out.println("m2 method");}
void m3(){System.out.println("m3 method");}
Test t1 = new Test1(); //abstract class reference variable Child class object
t1.m1(); //compile : Test runtime : Test1
t1.m2(); //compile : Test runtime : Test1
t1.m3() ; //compile : Test runtime : Test1
t1.m4() ; //compile : Test runtime : Test1
}
};
Example -3 :-
Abstract class contains abstract methods for that abstract methods provide the
implementation in child classes.
if the child class is unable to provide the implementation of all parent class abstract methods
at that situation declare that class with abstractmodifier then take one more child class to
complete the implementation of remaining abstract methods.
It is possible to declare multiple child classes but at final complete the implementation of all
methods.
39 | P a g e
{ Test3 t = new Test3();
t.m1();
t.m2();
t.m3();
t.m4();
}
};
Example-5:-
for the abstract methods it is possible to provide any return type(void, int, char,Boolean…..etc)
class Emp{};
abstract class Test1
40 | P a g e
{ abstract int m1(char ch);
abstract boolean m2(int a);
abstract Emp m3();
}
abstract class Test2 extends Test1
{ int m1(char ch)
{ System.out.println("char value is:-"+ch);
return 100;
}
};
class Test3 extends Test2
{ boolean m2(int a)
{ System.out.println("int value is:-"+a);
return true;
}
Emp m3()
{ System.out.println("m3 method");
return new Emp();
}
public static void main(String[] args)
{ Test3 t=new Test3();
int a=t.m1('a');
System.out.println("m1() return value is:-"+a);
boolean b=t.m2(111);
System.out.println("m2() return value is:-"+b);
Emp e = t.m3();
System.out.println("m3() return value is:-"+e);
}
};
Example-6:-
It is possible to override non-abstract as a abstract method in child class.
abstract class Test
{ abstract void m1(); //m1() abstract method
void m2(){System.out.println("m2 method");} //m2() normal method
};
abstract class Test1 extends Test
{ void m1(){System.out.println("m1 method");} //m1() normal method
41 | P a g e
abstract void m2(); //m2() abstract method
};
class FinalClass extends Test1
{ void m2(){System.out.println("FinalClass m2() method");}
public static void main(String[] args)
{ FinalClass f = new FinalClass();
f.m1();
f.m2();
}
};
Example:-
abstract class Test
{ public static void main(String[] args)
{ System.out.println("this is abstract class main");
}
};
Example-8:-
Constructor is used to create object (wrong definition).
Constructor is executed during object creation to initialize values to instance variables.
Constructors are used to write the write the functionality that functionality executed during
object creation.
There are multiple ways to crate object in java but if we are crating object by using “new” then
only constructor executed.
Note :- in below example abstract class constructor is executed but object is not created.
abstract class Test
{ Test()
{ System.out.println("abstrac calss con");
}
};
class Test1 extends Test
{ Test1()
{ super();
42 | P a g e
abstract class Test
{ abstract void m1();
};
class Test1 extends Test
{ void m1(){System.out.println("m1 method");}
};
Abstraction definition :-
The process highlighting the set of services and hiding the internal implementation is called
abstraction.
Bank ATM Screens Hiding the internal implementation and highlighting set of services like ,
money transfer, mobile registration,…etc).
43 | P a g e
Syllabus copy of institute just highlighting the contents of java but implementation there in
classed rooms .
We are achieving abstraction concept by using Abstract classes &Interfaces.
Encapsulation:-
The process of binding the data and code as a single unit is called encapsulation.
We are able to provide more encapsulation by taking the private data(variables) members.
To get and set the values from private members use getters and setters to set the data and to
Example:-
class Encapsulation
{ private int sid; private int
sname;
//mutator methods
public void setSid(int x)
{ this.sid=sid; }
public void setSname(String sname)
{ this.sname=sname; }
//Accessor methods
public int getSid(){ return sid; } ublic String getSname()
{ return sname; }
};
To access encapsulated use fallowing code:-
class Test
{ public static void main(String[] args)
{ Encapsulation e=new Encapsulation();
e.setSid(100);
e.setSname("ratan");
System.out.println(e.getSid());
System.out.println(e.getSname());
}
};
44 | P a g e
Main Method:-
45 | P a g e
Which of the fallowing declarations are valid:-
1. public static void main(String... a) --->valid
2. final strictfp static void mian(String[] Sravya) --->invalid
3. static public void mian(String a[]) --->valid
4. final strictfp public static main(String[] rattaiah) --->invalid
5. final strictfp synchronized public static void main(String... nandu)--->valid
Example-1:-
class Test
{ final strictfp synchronized static public void main(String...ratan)
{
System.out.println("hello ratan sir");
}
};
Example-2:-
class Test1
{ final strictfp synchronized static public void main(String...ratan)
{ System.out.println("Test-1");
}
};
class Test2
{ final strictfp synchronized static public void main(String...ratan)
{ System.out.println("Test-2");
}
};
class Test3
{ final strictfp synchronized static public void main(String...ratan)
{System.out.println("Test-3");
}
};
In above two example execute all [.class] files to check the output.
Example-3:-main method VS inheritance
class Parent
{ public static void main(String[] args) class Parent
{ { public static void main(String[] args)
System.out.println("parent class"); {
} System.out.println("parent class");
}; }
class Child extends Parent };
{ public static void main(String[] args) class Child extends Parent
{ {
System.out.println("child class"); };
}
};
In above two examples execute both Parent and Child [.class] files to check the output.
Example-4:-main method VS overloading
class Test
{ public static void main(String[] args)
46 | P a g e
{
System.out.println("String[] parameter main method start");
main(100);//1-argument ( int ) method calling
}
public static void main(int a)
{
main('r'); //1-argument ( char ) method calling
System.out.println("int main method-"+a);
}
public static void main(char ch)
{
System.out.println("char main method-"+ch);
}
}
Strictfp modifier:-
a. Strictfp is a modifier applicable for classes and methods.
b. If a method is declared as strictfp all floating point calculations in that method will
followIEEE754 standard. So that we will get platform independent results.
c. If a class is declared as stictfp then every method in that class will follow IEEE754standard so we
will get platform independent results.
Ex:- strictfp class Test{ //methods///} --->all methods fallows IEEE754
strictfp void m1(){} ---> m1() method fallows IEE754
Native modifier:-
a. Native is the modifier applicable only for methods.
b. Native method is used to represent particular method implementations there in non-java code
(other languages like C,CPP) .
c. Nativemethods are also known as “foreign methods”.
Examples:-
public final int getPriority();
public final void setName(java.lang.String);
public static native java.lang.Thread currentThread();
public static native void yield();
Command Line Arguments:-
The arguments which are passed from command prompt is called command line arguments. We
are passing command line arguments at the time program execution.
Example-1 :-
class Test
{
public static void main(String[] ratan)
{ System.out.println(ratan[0]+" "+ratan[1]);//printing command line arguments
System.out.println(ratan[0]+ratan[1]);
//conversion of String-int String-double
int a = Integer.parseInt(ratan[0]);
double d = Double.parseDouble(ratan[1]);
System.out.println(a+d);
}
};
47 | P a g e
D:\>java Test 100 200
100 200
100200
300.0
{
void m1(int... a) { System.out.println("Ratan"); }//var-arg method
public static void main(String[] args)
{
Test t=new Test();
t.m1(); //int var-arg method executed
t.m1(10);//int var-arg method executed
t.m1(10,20);//int var-arg method executed
}
}
Example-2:-
class Student
{ void classRoom(int... fee) {System.out.println("class room --> B.tech --> CSE"); }
public static void main(String[] ratan)
{
Student s = new Student();
s.classRoom(); //scholarship students
s.classRoom(30000); //counselling fee students
s.classRoom(100000,30000); //NRI student with donation + counselling fee
s.classRoom(100000,30000,40000);//NRI student donation+mediator fee+counselling
}
}
Example-3:-printing var-arg values
class Test
{ void m1(int... a)
{ System.out.println("Ratan");
for (int a1:a)
{System.out.println(a1); }
}
public static void main(String[] args)
{
Test t=new Test();
t.m1(); //int var-arg method executed
t.m1(10); //int var-arg method executed
t.m1(10,20); //int var-arg method executed
t.m1(10,20,30,40); //int var-arg method executed
65 | P a g e
}
}
Example-4:-var-arg VS normal arguments
class Test
{ void m1(int a,double d,char ch,String... str)
{ System.out.println(a+” ”+d+” ”+ch); //printing normal arguments
for (String str1:str)//printing var-arg by using for-each loop
{ System.out.println(str1);
}
}
public static void main(String... args)
65 | P a g e