Understanding OOP Concepts and Principles
Understanding OOP Concepts and Principles
1) Procedure Oriented
2) Object Oriented
Procedure Oriented
-> In Procedure Oriented programming language, we will develop functions &
procedures
-> If we want to add more functionality then we need to develop more functions
Object Oriented
-> If we want to develop a project using OOP language then we have to use Classes &
Objects
-> Any language which follows OOPS Principles is called as OOP Language
2) Abstraction
3) Polymorphism
4) Inheritance
Encapsulation
-> Encapsulation is used to combine our variables & methods as single entity / unit
Example:
class Demo {
//variables
// methods
Abstraction
-> Abstraction means hiding un-necessary data and providing only required data
Ex:-1:
Ex:-2:
Inheritence
-> Extending the properties from one class to another class is called as Inheritance
Note: In java, one child can't inherit properties from two parents at a time
Class
-> Class is a plan or model or template
-> Once class is created then we can create any [Link] objects for a class
-> 'class' keyword is used to create Classes in java
class <ClassName> {
// variables
// methods
Object
-> Any real-world entity is called as Object
-> Without having the class, we can't create object (class is mandatory to create
objects)
-> If object is not using then garbage Collector will remove that object from heap
-> Garbage Collector is responsible for memory clean-up activities in JVM heap area.
-> We can get hash code of the object by calling [Link] class hashCode ()
method.
[Link] ( );
Note: [Link] class is by default parent class for all java classes.
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
Variables
-> Variables are used to store the data
int a = 10 ;
b) static variables
c) local variables
Instance variables
-> Variables which are declared inside the class and outside the method are called as
instance variables
-> Instance variables can be accessed by all the methods available in the class that’s
why they are called as Global Variables.
-> When we create the object, then only memory will be allocated for instance
variables
Note: If we create 2 objects, then 2 times memory will be allocated for instance
variables
-> If we don't initialize instance variable, it will be initialized with default value based
on datatype when the object is created
-> Every Object will maintain its own copy of the instance variable
public class User {
int age;
[Link] = 20;
[Link]([Link]);
[Link] = 25;
[Link]([Link]);
Static Variables
-> The variables which are declared inside the class and outside the method with
'static' keyword are called as static variables
-> When class is loaded into JVM then immediately memory will be allocated for
static variables
-> Memory will be allocated for static variables only once when the class is loaded
into JVM
-> All objects of the class will maintain same copy of the static variables
-> Static variables we will access using class name
String name;
String email;
long phno;
[Link] = "ashokit";
[Link] = "Ankit";
[Link] = "Goutham";
-> If we want to store same value for all objects then use static variable
Local Variables
-> The variables which are declared inside the method or constructor or block are
called as Local Variables
-> If we declare a variable with in the method, then that variable can be used /
accessed only with in that method
-> If we create a variable with in the method, memory will be allocated for that
variable when that method is executing. After that method execution completed,
local variable will be deleted from memory
class Demo {
int a = 20;
int b = 20;
[Link](a);
[Link](b);
Methods
-> Methods are used to perform some operation / action
-> In a class we can write any [Link] methods including main method
-> If we want to execute our method then we have to invoke / call our methods from
main ( ) method.
Syntax:
//logic
return value;
1) Method Declaration
2) Method Body
syntax:
What is returntype ?
-> returntype is data type that indicates what type of value is return by the particular
method.
-> returntype can be any primitive type or array type or reference type
->if method does not return any value then return type must be specified using a java
keyword called "void ".
->we can write 0 or more number of parameters of any primitive type or array type
or reference type
syntax:
//statements;
return value;
-> Here we can write 0 or more number of statements in between the pair of curly
braces.
-> When we write 0 statements then it is called as null implementation
->if the return type is specified as other than void then we must return a value from
our method using java keyword called "return ".
syntax:
return value;
->the datatype of the value we return must be match with the datatype that we
specify as return type.
->but if return type specified as void then we must not write any return value
statement.
-> In java we can create any number of methods which are in any of the following 4
combinations of methods
void hello ( ) {
[Link]("Hello My Friend");
}
2. Method without return type , with parameters
S.o.p(name);
int c = a + b ;
return c;
// take person age as input, if person age >=18 then return true else return false
if ( age >= 18 ) {
return true;
} else {
return false;
}
Types of Methods
=> Methods are divided into 2 types
-> When we write methods in java class, by default jvm will not execute them
Note: JVM will start our program execution from main method. Main method is
called as entry point for JVM execution
// this is valid
void m1 ( ) {
// this is valid
// this is valid
int c = a + b;
return c;
}
// this is valid
return a + b;
// this is valid
return a / b ;
// below method is invalid (method return type is int but it is trying to return string
value)
Stirng s1 = [Link]( ) ;
return s1;
// this is valid
if (a > b )
return true;
else
return false;
}
// this is valid
return a > b ;
return "hi";
// this is valid
boolean m3( ) {
return true ;
// this is valid
[Link](arr);
[Link]("Hi, i am a student");
[Link]();
[Link]();
void hello() {
[Link]("Hello My Friend...");
[Link]("Good Evening..");
import [Link];
//object creation
int[] ar = { 1, 2, 3 };
[Link](ar);
[Link]("ashok", "it");
[Link](name);
}
[Link]([Link](arr));
package azienit;
public class findMaxElement {
public static void main(String[] args) {
int arr[] = {5, 2, 6, 7, 9};
findMaxElement x = new findMaxElement();
[Link]([Link](arr));
}
package azienit;
public class findLength {
public static void main(String[] args) {
findLength fl = new findLength();
String n = "Prakash";
[Link]([Link](n));
}
int Length(String name) {
int length = [Link]();
return length;
}
}
3) Write a java method to perform sum of two numbers
package azienit;
public class Sum {
public static void main(String[] args) {
Sum s = new Sum();
int a = 10;
int b = 20;
[Link]([Link](a, b));
}
int add(int a, int b) {
return a + b;
}
}
4) Write a java method to concat firstname and lastname
package azienit;
public class Name {
public static void main(String[] args) {
Name n = new Name();
[Link]([Link]("Prakash", "
chaurasiya"));
}
package azienit;
public class Vote {
public static void main(String[] args) {
Vote v = new Vote();
[Link](23);
}
void chect(int age) {
if(age > 18) {
[Link]("elgible for vote");
} else {
[Link]("not elgible for vote");
}
}
}
5) Write a java method to reverse given array
package azienit;
public class Method1 {
public static void main(String[] args) {
Method1 m = new Method1();
int arr[] = {3, 2, 23, 12, 78, 56, 9, 65};
[Link](arr);
}
void reverseArray (int arr[]) {
int temp = 0;
for(int i=0; i<[Link]/2; i++) {
temp = arr[i];
arr[i] = arr[[Link]-1-i];
arr[[Link]-1-i] = temp;
}
for(int x : arr) {
[Link](x +" ");
}
}
}
6) Write a java method to convert the name into uppercase characters
package azienit;
public class Method2 {
public static void main(String[] args) {
Method2 m = new Method2();
String name = "prakash chaurasiya";
[Link]([Link](name));
}
String s= [Link] ( ar ) ;
String s1 = [Link] ( );
// int length ( )
int x = [Link] ( ) ;
boolean z = [Link]("it");
//instance method
int add(int a, int b) {
int c = a + b;
return c;
}
}
-> For every Obect jvm will assign one unique hashcode
-> Java is a OOP language, so everything will be represented in the form of Objects
-> In Real-time Projects, mainly our methods will deal with Objects only
[Link](s);
}
void print(Student2 s) {
[Link]([Link]+ " " +[Link]);
}
}
class Student2 {
int id;
String name;
}
// Take employee class with id and salary as properties
// Take Driver class and write the method to print employee object data & call the
print method from main method
package azienit;
public class Driver2 {
public static void main(String[] args) {
Driver2 d = new Driver2();
[Link](emp1);
[Link](emp2);
}
void print(employee e) {
[Link]([Link]+ " " +[Link]);
}
}
class employee{
int id;
double salary;
}
// Take Product class with productId, productName, productPrice as properties
package azienit;
public class Driver3 {
public static void main(String[] args) {
Driver3 d = new Driver3();
[Link](pr1);
[Link](pr2);
}
void print(Product p) {
[Link]([Link]+" "+[Link]+" "+[Link]);
}
}
class Product {
int pid;
String pname;
double pprice;
}
// Take Docter class with docterName, docterAge as properties
package azienit;
public class Driver4 {
public static void main(String[] args) {
Driver4 d = new Driver4();
[Link](dr);
}
class Docter {
String name;
int age;
}
// Take a Player class with id, name, age properties
package azienit;
public class Driver5 {
public static void main(String[] args) {
Driver5 d = new Driver5();
[Link](p1);
}
void print(player p) {
[Link]([Link]+" "+[Link]+" "+[Link]);
}
}
class player {
int id;
String name;
int age;
}
// write a java method which will give Person object with data
package azienit;
public class Driver6 {
public static void main(String[] args) {
Driver6 d = new Driver6();
Person p = d.m1();
[Link]([Link]+" "+[Link]+" "+[Link]);
Person m1() {
Person p = new Person();
[Link] = 101;
[Link] = "Raju";
[Link] = 20;
return p;
}
}
class Person {
int id;
String name;
int age;
}
// Write a java method to return College data (id, name)
package azienit;
public class Driver7 {
public static void main(String[] args) {
Driver7 d = new Driver7();
College p = d.m1();
[Link]([Link]+" "+[Link]);
}
College m1() {
College c = new College();
[Link] = 101;
[Link] = "Prakash";
return c;
}
}
class College {
int id;
String name;
}
Raju Data ( 101, Raju, 30 )
// Write a java method which will take id as input. if id is 101 then method should
return Raju object
package azienit;
public class Driver8 {
public static void main(String[] args) {
Driver8 d = new Driver8();
Person p = d.m1(102);
[Link]([Link]+"--"+[Link]+"--"+[Link]);
}
if(id == 101) {
[Link] = 101;
[Link] = "raju";
[Link] = 20;
} else if(id == 102){
[Link] = 102;
[Link] = "Rani";
[Link] = 18;
}
return p;
}
}
class Person{
int id;
String name;
int age;
}
// write a java method which will return cricket player data based on player number
7 ----> Dhoni
18 ---> Kohli
package azienit;
public class Driver9 {
public static void main(String[] args) {
Driver9 d = new Driver9();
players p = d.m1(7);
[Link]([Link]+"--"+[Link]+"--"+[Link]);
}
if(id == 7) {
[Link] = 7;
[Link] = "Dhoni";
[Link] = 41;
} else if(id == 18) {
[Link] = 18;
[Link] = "Kohli";
[Link] = 34;
} else if(id == 45) {
[Link] = 45;
[Link] = "Rohit";
[Link] = 37;
}
return p;
}
class players {
int id;
String name;
int age;
}
// Write a java method to return University data based on unvesity ID
package azienit;
public class University {
int id;
String name;
String m2() {
String s = "Hello";
return s;
}
static University m1(int id) {
University u = new University();
if(id==101) {
[Link] = 101;
[Link] = "Oxford";
} else if(id == 102) {
[Link] = 102;
[Link] = "Standford";
}
return u;
}
}
// Write a java class with two methods
Approach-1:
// logic
Approach-2 :
// logic
Person[ ] m2(){
// logic
}
package azienit;
public class Person {
int id;
String name;
Person[] m2() {
Person p1 = new Person();
[Link] = 101;
[Link] = "Raju";
return arr;
}
p.m1(p1, p2);
Object: Physical Entity. It is used to access variables & methods of the class
-> When object created, memory will be allocated for instance variables
-> Every object will maintain its own copy of instance variables
-> When class is loaded then memory will be allocated for static variables
-> When method is invoked then only memory will be allocated for local variables
Note: If we write return type for the constructor then it will become method
Demo ( ) {
// logic
Note: At the time of object creation our class Constructor will be executed.
Constructor is mandatory to create the object.
Note: If we don't write the constructor in class, then java compiler will add one
default constructor to our class.
-> We can check default constructor for the class using below command
Note: If we write constructor in the class, then compiler will not add any constructor.
-> Constructors are divided into 2 types
class Student {
Student ( ) {
...
2) Parameterized Constructor
class Student {
...
class Employee {
[Link](i + j);
}
this keyword
-> this is a predefined keyword in java
class Employee {
String name;
float salary;
[Link] = name;
[Link] = salary;
int id;
String name;
int age;
String gender;
[Link] = id;
[Link] = name;
[Link] = age;
[Link] = gender;
Constructor Overloading
-> Writing more than one constructor with different parameters is called as
Constructor Overloading
1) public
2) private
3) protected
4) default
public: It is used to specify global access for classes, variables, methods and
Constructors
Note: public means anybody can access from inside and outside the class also.
private: It is used to specify local access (with in the class). Private variables, private
methods, private constructors can't be accessed outside of the class.
-> We can take constructor as private (nobody can create obj from outside of cls)
-> We can take method as private (nobody can call our method from outside of cls)
Note: To make our java class as Singleton, we will use private constructor. The java
class which is having only one object is called as Singleton class.
protected: Protected members can be accessed in same package & its sub classes
default: default members can be accessed in same package. When we don't specify
any modifier then it comes under default modifier.
Note: only public and default modifiers are allowed for classes. private and protected
are not allowed.
Note: If we use 'public' for the class name then class name & file name should be
same. We should have only one public class in the java file.
Inheritance: The process of extending properties from one class to another class is
called as inheritance.
-> We will combine variables & methods as one single unit using Class
Example:
[Link] = accNum;
return [Link];
[Link] = name;
return [Link];
}
public class Test {
[Link](797979);
[Link]("Ashok");
Inheritance
-> The process of extending the properties from one class to another class is called as
Inheritance
-> From which class we are extending the properties that class is called as 'Parent' or
'Super' or 'Base' class
-> The class which is extending the properties is called as 'Child class' or 'Sub class' or
'Derived' class
Example:
class User {
// properties
// methods
Note: In above example 'User' class is acting as Parent class and Student class is
acting as Child class.
int id;
String name;
int rank;
[Link] = 1;
[Link] = 101;
[Link] = "Bhanu";
int rank;
[Link] = 101;
[Link] = "Raj";
int id;
String name;
void m1() {
}
public class Employee extends User {
void m2() {
emp.m1();
emp.m2();
-> Whenever we create child class object, then first it will execute parent class zero-
param constructor and then it will execute child class constructor.
-> Child should be able to access parent properties hence parent constructor will
execute first to initialize parent class properties.
Example:
public class User {
int id;
String name;
public User() {
double salary;
public Employee() {
void m2() {
[Link] = 101;
[Link] = "John";
// initialing child class properties using its own obj
[Link] = 4500.00;
Types of Inheritance
-> Inheritance is divided into multiple types
1) Single Level
2) Multi Level
4) Hierarchical
Multiple Inheritance: If one child having more than one parent (Java doesn't support
to avoid ambiguity)
Note: For every java class, [Link] class will act as Parent either directly or
in-directly
-> If our class doesn't have any parent then [Link] will become parent
directly
-> If our class having parent then [Link] will become parent in-directly
Note: Every java class can access methods available in [Link] class.
class Parent {
void m1() {
void m2() {
return 101;
void m1() {
void m2() {
super.m2();
}
}
c.m1();
c.m2();
Note: In inheritance always priority will be given for Child class / Sub class object. If
child class doesn't contain that method then priority will be given to Parent class
method.
Polymorphism
Poly ----> Many
-> If any object is exhibiting multiple behaviours based on the Situation then it is
called as Polymorphism.
Ex: Overloading
Ex: Overriding
Method Overloading
-> The process of writing more than one method with same name and different
parameters is called as Method Overloading.
=> When methods are performing same operation then we should give same name
hence it will improve code readability.
Ex:
=> In Method Overloading scenario, compiler will decide method should be called.
For example if we write like below then program will fail it compilation stage.
Method Overriding
-> The process of writing same methods in Parent class & Child class is called as
Method Overriding.
class Parent {
void m1( ) {
// logic
}
class Child extends Parent {
void m1 ( ){
//logic
c.m1 ( );
Note: When we don't want to execute Parent method implementation, then we can
write our own implementation in child class using method Overriding.
class RBIBank {
boolean checkElgibility() {
return true;
double getHomeLoanRofi() {
return 10.85;
}
public class SBIBank extends RBIBank {
double getHomeLoanRofi() {
return 12.85;
if (status) {
return msg;
} else {
[Link](msg);
}
// Method Overriding Example with User-Defined Objects and String Objects
Note: Object class equals ( ) method will compare address of the objects where String
class equals ( ) method will compare content of the objects.
class User {
int id;
String name;
void speak ( ){
[Link] = 10;
[Link] = "Raju";
[Link] ( );
}
}
class Engine {
int id;
String name;
String fuelType;
void start ( ){
[Link]("Engine Starting....");
class Car {
void drive ( ){
[Link] ( );
[Link]("Journey Started");
final keyword
-> final is a reserved keyword in java
1) class level
2) variable level
3) method level
-> final classes can't be inherited. We can't extend properties from final classes. Final
classes are immutable.
Example:
public class User extends String { // invalid because String is final class
-> final variables are nothing but constants. Final variable value can't be modified.
pi = 4.32; // invalid
Method Types
-> In java we can write 2 types of methods
1) Concrete Method
2) Abstract Method
public void m1 ( ) {
-> The method which doesn't contain body is called as 'Abstract method'
Note: By using 'abstract' keyword we can create abstract methods & abstract
classes.
Interfaces
-> Interfaces are used to achieve loosely coupling & abstraction
-> Once interface is created then anybody can provide implementation for the
interface
-> Implementing interface means overriding 'interface abstract methods'
Note: One java class can extend properties from only one class and it can implement
multiple interfaces at a time.
Interface Example
public interface Bank {
}
public class AxisBank implements Bank {
}
=> We can't create Object for interface
=> Interface reference variable can hold its implementation class object.
Ex:
Bank b = new Kotak ( ) ;// in-valid because it is not implementation class for Bank
=> When method is taking interface a parameter that means that method is
expecting interface implementation class object as parameter.
public void m1 (Bank b ) { // loosely coupled bcz we can pass any impl cls obj
public void m1(AxisBank b){ // tightly coupled bcz we have to pass only AxisBank obj
=> When method is having Interface as a return type that means that method will
return interface implementation object as return type
public Bank m2 ( ) { // loosely coupled bcz we can return any impl cls obj
public HdfcBank m2 ( ) { // tighthly coupled bcz only HdfcBank obj shud be returned
-> If interface doesn't contain any method then that interface is called as 'Marker
Interface'
-> If our class implements pre-defined marker interface then JVM will treat our
classes as special classes and JVM will provide special functionality based on the
marker interface we have implemented.
Note: We can create our own marker interfaces but there is no use because JVM
don't know abt our marker interfaces.
-> The interface which contains only one abstract method is called as Functional
Interface.
-> In Interface we can declare variables also, by default they are public static final.
}
Abstract Classes
-> The class which contains both concrete and abstract methods is called as abstract
class.
-> We can write constructor in abstract class but we can't create Object
-> When we extend properties from abstract class then it is mandatory to override all
abstract methods of that class
-> Abstract class constructor will be executed when we create object for child class.
public DieselMachine() {
[Link]("DieselMachine-Constructor");
[Link]("Machine starting....");
public Machine() {
[Link]("Machine Constructor");
}
@Override
[Link]();
[Link]();
=> abstract means override in child where as 'final' means don't override .
=> To create interface we will use 'interface' keyword
=> Abstract classes can contain both abstract methods & concrete methods
=> When we implement any interface then we have to implement all the abstract
methods of that interface
=> When we extend abstract class, we need override all abstract methods
=> Abstract class constructor will be executed when we create object for sub class.
=> If interface contains only one method then it is called Functional Interface
=> If interface doesn't have any method then it is called as Marker interface
=> When we don't know implementation for methods then we will go for Interfaces
=> When we know partial implementation for methods then we will go for abstract
classes
Blocks in java
-> Block means some part or some piece of information or some piece of code
1) instance block
2) static block
Instance Block
-> If you want to execute some piece of code when object is created then we can go
for instance block
syntax:
// stmts
static Block
-> If you want to execute some piece of code when class is loaded into JVM then we
can go for static block
syntax:
static
// stmts
}
Q) What is static control flow & instance control flow in java program ?
-> When we run java program, JVM will check for below static members & JVM will
allocate memory for them in below order
a) static variables
b) static methods
c) static blocks
-> Once memory allocation completed for static members then it will start execution
in below order
a) static block
b)static method (if we call) - only main method will execute automatically by
jvm
c) static variable
-> static variables can be accessed directly in static blocks and static methods.
Note: If we want to access any instance method or instance variable in static area
then we should create object and using that object only we can access. We can't
access directly without object.
-> Instance control flow will begin when object is created for a class
a) instance variables
b) instance methods
c) instance blocks
-> Once memory allocation completed then execution will happen in below order
a) instance block
b) constructor
Note: static members can be access directly in instance areas because for static
members memory already allocated at the time of class loading.
public Demo() {
static {
}
[Link] class
-> Object is a pre-defined class available in [Link] package
-> Object class will act as super class for all the classes in java either directly or in-
directly
Note: If our class doesn't have any super class then Object class will become direct
Super class. If our class having any super class then Object class will become in-direct
super class.
-> Object class having 11 methods, those 11 methods are by default available for
every java object.
5) int hashCode( )
6) String toString( )
7) notify ( )
8) notifyAll ( )
9) void wait ( )
-> When we print any object or when we call toString ( ) method by default it will call
Object class toString ( ) method
Output: Student@15db9742
-> If we don't like this implementation, then we can override toString ( ) method in
our class like below
int id;
String name;
[Link] = 101;
[Link] = "John";
[Link]([Link]());
String s1 = new String("hi");
[Link](s1);
-> If we don't want to execute Object class hashCode ( ) method then we can
override hashCode ( ) method in our class.
int id;
String name;
[Link] = 101;
[Link] = "John";
[Link](s); // toString ( ) will be called
[Link]([Link]());
return id;
Note: Object class equals( ) method will compare address of the object not content.
int id;
String name;
[Link] = id;
[Link] = name;
}
public static void main(String[] args) {
Note: In String class equals ( ) method overriden to compare content of objects thats
why in above program for Strings we are getting 'true' as ouput. For Student class it is
checking address hence we are getting 'false' as output.
-> If we want to compare content of our Student objects then we need to override
like below
int id;
String name;
[Link] = id;
[Link] = name;
@Override
int result = 1;
return result;
}
@Override
if (this == obj) // s1 == s2
return true;
return false;
if (getClass() != [Link]())
return false;
return false;
if ([Link] != null)
return false;
return false;
}
Class getClass ( ) method
-> This method is used to get Runtime instance of class
[Link]([Link]());
[Link](object);
clone ( ) method
-> This method is used to create duplicate object for the given object
-> If we want to clone any object then that class should implement Cloneable
interface which is marker interface.
-> If your class implements Cloneable interface then only JVM will allow you to clone
the object of that class.
[Link](s);
[Link](clone);
Ans)
finalize ( ) method
-> When garbage collector removing any object from JVM then it will call finalize ( )
method
finalize ( )
clone ( )
equals ( )
hashCode ( )
toString ( )
getClass ( )
notify ( )
notifyAll ( )
Note: newInstance ( ) method available in Class it is used to create obj for a class
Object ---> This is also predefined class available in [Link] package. Default parent
for all java classes. It contains 11 methods. Every java class can access Object class
methods by default.
OOPS Summary
1) Procedural Oriented Language (PoP)
3) Classes
4) Objects
9) Constructor Overloading
12) Encapsulation
13) setter methods & getter methods
14) Inheritence
17) Polymorphism
21) Abstraction
22) Interfaces
25) Blocks