0% found this document useful (0 votes)
52 views78 pages

Understanding OOP Concepts and Principles

The document provides an overview of Object-Oriented Programming (OOP) concepts, contrasting it with Procedure-Oriented Programming (POP). It explains key OOP principles such as encapsulation, abstraction, polymorphism, and inheritance, along with the definitions and roles of classes and objects. Additionally, it covers variable types, method structures, and examples of method implementations in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views78 pages

Understanding OOP Concepts and Principles

The document provides an overview of Object-Oriented Programming (OOP) concepts, contrasting it with Procedure-Oriented Programming (POP). It explains key OOP principles such as encapsulation, abstraction, polymorphism, and inheritance, along with the definitions and roles of classes and objects. Additionally, it covers variable types, method structures, and examples of method implementations in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter-4 : OOPS (Object Oriented Programming System)

-> Programming languages are divided into 2 types

1) Procedure Oriented

Ex: C, Cobol, Pascal etc.....

2) Object Oriented

Ex: Java, C#, Python etc.....

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

-> Maintaining & managing more functions is difficult task

-> In Pop, data is exposed globally

-> In Pop, there is no security

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

-> Object oriented languages provides security for our data

-> The main advantage of OOPS is code re-usability


OOPS Principles
1) Encapsulation

2) Abstraction

3) Polymorphism

4) Inheritance

Encapsulation
-> Encapsulation is used to combine our variables & methods as single entity / unit

-> Encapsulation provides data hiding

-> We can achieve encapsulation using Classes

Example:

class Demo {

//variables

// methods

Abstraction
-> Abstraction means hiding un-necessary data and providing only required data

-> We can achieve Abstraction using interfaces & abstract classes

Ex: we will not bother about how laptop working internally

We will not bother about how car engine starting internally


Polymorphism
-> Exhibiting multiple behaviours based on situation is called as Polymorphism

Ex:-1:

In below scenario + symbol having 2 different behaviours

10 + 20 ===> 30 (Here + is adding)

"hi" + "hello" ==> hihello (here + is concatenating)

Ex:-2:

 When i come to class i will behave like a trainer


 When i go to office i will behave like a employee
 When i go to home i will behave like a family member

Inheritence
-> Extending the properties from one class to another class is called as Inheritance

Ex: child will inherit the properties from parent

-> The main aim of inheritance is code re-usability

Note: In java, one child can't inherit properties from two parents at a time

Class
-> Class is a plan or model or template

-> Class is a blue print of object

-> Class is used to declare variables & methods

-> Project means collection of classes

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

-> Classes will not exist physically

Object
-> Any real-world entity is called as Object

-> Objects exist physically

-> Objects will be created based on the Classes

-> Without having the class, we can't create object (class is mandatory to create
objects)

-> Object creation means allocating memory in JVM

-> 'new' keyword is used to create the objects

ClassName refVariable = new ClassName ( );

User u1 = new User ( );

User u2 = new User ( ) ;

-> Objects will be created by JVM in the runtime

-> Objects will be created in heap area.

-> 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.

-> Garbage Collector will remove un-used objects from heap.


-> Garbage Collector will be managed & controlled by JVM only.

Note: Programmer doesn’t have control on Garbage Collector.

What is Hash Code


-> JVM will assign unique hash code for every object

-> No two objects will have same hash code

-> 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.

public class User {

public static void main(String[] args) {

User u1 = new User();

[Link]([Link]());

User u2 = new User();

[Link]([Link]());

User u3 = new User();

[Link]([Link]());

}
Variables
-> Variables are used to store the data

int a = 10 ;

User u1 = new User ( );

Student s1 = new Student ( );

-> Variables are divided into 3 types

a) Global Variables / instance variables / non-static variables

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.

-> Initialization is optional for instance variables

-> Instance variables are called as Object 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;

public static void main(String[] args) {

User raju = new User();

[Link] = 20;

[Link]([Link]);

User rani = new User();

[Link] = 25;

[Link]([Link]);

User ashok = new User();

Static Variables
-> The variables which are declared inside the class and outside the method with
'static' keyword are called as static variables

-> Static variables are class level 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

public class Student {

String name;

String email;

long phno;

static String institute;

public static void main(String[] args) {

[Link] = "ashokit";

Student ankit = new Student();

[Link] = "Ankit";

Student goutham = new Student();

[Link] = "Goutham";

When to declare variable as static or non-static ?


-> If we want to store different value based on object then use instance variable

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

-> Before using local variables, we have to initialize them

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

public static void main(String[ ] args){

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

Note: JVM will always invokes main ( ) method

-> If we want to execute our method then we have to invoke / call our methods from
main ( ) method.
Syntax:

returnType <methodName> (param1, param2, para3..... paramN) {

//logic

return value;

-> Every method contains 2 parts

1) Method Declaration

2) Method Body

What is Method Declaration ?


Method declaration means we are going to decide what the name of the method is,
what the parameters it will take are and what kind of value is return by the method.

syntax:

returntype methodname (list of parameters);

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 ".

->specifying returntype is mandatory


What is method name ?
-> To identify and access the method there is a suitable name is given for a method
which is called as method name.

->a method name can be any valid java identifier.

-> specifying method name is mandatory

What are method parameters ?


->parameters are the variables that will receive the values that are passed into the.
particular method on which data method will perform the operations.

->we can write 0 or more number of parameters of any primitive type or array type
or reference type

->specifying parameters is optional.

Method body / Method Definition / Method implementation


-> Method body means we are going to write the group of statements that are
executed by the method.

-> A method body can be written in between a pair of curly braces

syntax:

returntype methodname(list of parameters)

//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

1. Method without return type, without parameters

2. Method without return type, with parameters

3. Method with return type, without parameters

4. Method with return type, with parameters

1. Method without return type, without parameters

// Write a method to print a msg on console

void hello ( ) {

[Link]("Hello My Friend");

}
2. Method without return type , with parameters

// take 2 names as input, concat them and print on console

void fullname (String fname, String lname) {

String name = fname + lname;

S.o.p(name);

3. Method with return type, without parameters

// Take 2 numbers as input and return sum as output

int add ( int a, int b ) {

int c = a + b ;

return c;

4. Method with return type, with parameters

// take person age as input, if person age >=18 then return true else return false

boolean check (int age ){

if ( age >= 18 ) {

return true;

} else {

return false;

}
Types of Methods
=> Methods are divided into 2 types

1) Instance methods ---> Object level methods

2) static methods ----> Class level method

->instance method will be called by using Object

->static method will be called by using Class

-> When we write methods in java class, by default jvm will not execute them

-> To execute our methods we have to call 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 ( ) {

// below method is valid

// this is valid

void m1 (int a, float f){

// this is valid

int add (int a, int b){

int c = a + b;

return c;

}
// this is valid

int add (int a, int b){

return a + b;

// this is valid

int div (int a, int b){

return a / b ;

// below method is invalid (method return type is int but it is trying to return string
value)

int m1 (String name){

Stirng s1 = [Link]( ) ;

return s1;

// this is valid

boolean m2 ( int a, int b){

if (a > b )

return true;

else

return false;

}
// this is valid

boolean m2 (int a, int b){

return a > b ;

// this is invalid because it is having 2 return types

String void m2(){

return "hi";

// this is valid

boolean m3( ) {

return true ;

// this is valid

void c1 (int [ ] arr ){

[Link](arr);

Example: Method implementation

public class Student {

public static void main(String[] args) {

[Link]("Hi, i am a student");

Student s1 = new Student();

[Link]();
[Link]();

void hello() {

[Link]("Hello My Friend...");

static void greet() {

[Link]("Good Evening..");

Example: Method Implementation

import [Link];

public class Methods {

public static void main(String[] args) {

//object creation

Methods m = new Methods();

int[] ar = { 1, 2, 3 };

[Link](ar);

[Link]("ashok", "it");

void fullname(String fname, String lname) {

String name = fname + lname;

[Link](name);
}

void print(int[] arr) {

[Link]([Link](arr));

1) Write a java method to find max element in given array

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

int Max(int arr[]) {


int max = 0;
for(int i=0; i<[Link]; i++) {
if(arr[i]>max) {
max = arr[i];
}
}
return max;
}
}
2) Write a java method to find length of given name

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

String concatNames(String fname, String lname) {


return fname + lname;
}
}
5) Write a java method to display person is elgible for vote or not

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 ConvertUppercase(String name) {


return [Link]();
}
}
int ar[ ] = {1,2,3};

String s= [Link] ( ar ) ;

String str = new String("hi");

StringBuffer sb = new StringBuffer(str);

String s1 = [Link] ( );

String line = [Link] ( );

String name = "ashokit";

// int length ( )

int x = [Link] ( ) ;

// boolean endsWith (String str)

boolean z = [Link]("it");

// char charAt (int index)

char ch = [Link] (0);


package azienit;
public class Driver {
public static void main(String[] args) {
Driver d = new Driver(); // object creation
int x = [Link](10, 20);// calling the method
[Link](x);// printing the output
}

//instance method
int add(int a, int b) {
int c = a + b;
return c;
}
}

Working with Methods using Objects


-> Object means physical entity

-> Objects are used to store the data

-> Object will be created based on class name

-> To create the object we will use 'new' operator

-> Object will be stored in heap area

-> For every Obect jvm will assign one unique hashcode

-> In real-time projects, data will play the major role

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

// Write a java method to print data available in the Student object


package azienit;
public class Driver1 {
public static void main(String[] args) {
Driver1 d = new Driver1();

Student2 s = new Student2();


[Link] = 101;
[Link] = "raju";

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

employee emp1 = new employee();


[Link] = 101;
[Link] = 60000;

employee emp2 = new employee();


[Link] = 102;
[Link] = 60000;

[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

// Create Driver class with print ( ) method to print product data

package azienit;
public class Driver3 {
public static void main(String[] args) {
Driver3 d = new Driver3();

Product pr1 = new Product();


[Link] = 101;
[Link] = "Tea";
[Link] = 100;

Product pr2 = new Product();


[Link] = 102;
[Link] = "Coffea";
[Link] = 150;

[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

// Create Driver class with print ( ) method to print Docter data

package azienit;
public class Driver4 {
public static void main(String[] args) {
Driver4 d = new Driver4();

Docter dr = new Docter();


[Link] = 25;
[Link] = "neeraj";

[Link](dr);
}

void print(Docter dr) {


[Link]([Link]+" "+[Link]);
}
}

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

player p1 = new player();


[Link] = 101;
[Link] = "Prakash";
[Link] = 23;

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

Rani Data ( 102 , Rani, 32 )

// Write a java method which will take id as input. if id is 101 then method should
return Raju object

if id is 102 then method should return Rani 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]);
}

Person m1(int id) {


Person p = new Person();

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

Player Data --> id, name, age

7 ----> Dhoni

18 ---> Kohli

45 ---> Rohit Sharma

package azienit;
public class Driver9 {
public static void main(String[] args) {
Driver9 d = new Driver9();
players p = d.m1(7);

[Link]([Link]+"--"+[Link]+"--"+[Link]);
}

players m1(int id) {


players p = new players();

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

101 -----> id - 101, name - Oxford

102 ----> id- 102, name - Standford

package azienit;
public class University {
int id;
String name;

public static void main(String[] args) {


University u = m1(101);
[Link]([Link]+"--"+[Link]);

String str = u.m2();


[Link](str);
}

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

// first method should take 2 Person objects as input

Approach-1:

void m1(Person p1, Person p2){

// logic

Approach-2 :

void m1 (Person[ ] p){

// logic

// second method should give 3 Person Objects as output

Person[ ] m2(){

// logic

}
package azienit;
public class Person {
int id;
String name;

Person[] m2() {
Person p1 = new Person();
[Link] = 101;
[Link] = "Raju";

Person p2 = new Person();


[Link] = 102;
[Link] = "Rani";

Person p3 = new Person();


[Link] = 103;
[Link] = "Anil";

Person[] arr = {p1, p2, p3};

return arr;
}

void m1(Person p1, Person p2) {


[Link]([Link]+"--"+[Link]);
[Link]([Link]+"--"+[Link]);
}

public static void main(String[] args) {


Person p = new Person();// obj 1 created

Person p1 = new Person(); // obj 2 created


[Link] = 101;
[Link] = "Raju";

Person p2 = new Person(); //obj 3 created


[Link] = 102;
[Link] = "Rani";

p.m1(p1, p2);

Person[] arr = p.m2();


for(Person person : arr) {
[Link]([Link]+" "+[Link]);
}
}
}
Class: It is a plan or model. It contains variables & Methods

Object: Physical Entity. It is used to access variables & methods of the class

Variables: Used to store the data

- instance variables (inside class, outside method without static keyword)

-> When object created, memory will be allocated for instance variables

-> Every object will maintain its own copy of instance variables

- static variables (inside class, outside method with static keyword)

-> When class is loaded then memory will be allocated for static variables

- local variables (inside the method)

-> When method is invoked then only memory will be allocated for local variables

-> Before using local variable, we have to initialize that

Methods: To perform some operation

- instance method ---> We will call by using object

- static method -----> We will call by using Classname

- Method Declaration (Signature) ---> return type + name + list of parameters

- Method Definition (Body) ----> logic


Constructors
-> Constructor is a special method in java which is used to initialize current class
instance variables

-> Constructor name should be same as class name

-> Constructor shouldn’t have any return type(not even void)

Note: If we write return type for the constructor then it will become method

Syntax : class Demo {

Demo ( ) {

// logic

Demo d = new Demo ( );

Note: At the time of object creation our class Constructor will be executed.
Constructor is mandatory to create the object.

-> Object creation means calling the constructor (new Demo( ) )

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

> javap classname

Note: If we write constructor in the class, then compiler will not add any constructor.
-> Constructors are divided into 2 types

1) Zero Param Constructor / Default Constructor

- Constructor without parameters

class Student {

Student ( ) {

...

2) Parameterized Constructor

- Constructor which contains 1 or more parameters

class Student {

Student (int i, int b ) {

...

class Employee {

public Employee(int i, int j) {

[Link](i + j);

public static void main (String[] args) {

Employee emp = new Employee(100, 200);

}
this keyword
-> this is a predefined keyword in java

-> It is used to represent current class object

class Employee {

String name;

float salary;

public Employee(String name, float salary) {

[Link] = name;

[Link] = salary;

[Link]([Link] + "--" + [Link]);

public static void main(String[] args) {

Employee emp = new Employee("Raju", 55000.00f);

public class Student {

int id;

String name;

int age;

String gender;

public Student(int id, String name, int age, String gender) {

[Link] = id;
[Link] = name;

[Link] = age;

[Link] = gender;

[Link]([Link] + "-" + [Link] + "-" + [Link] + "-" +


[Link]);

public static void main(String[] args) {

Student s1 = new Student(1, "Raju", 20, "Male");

Student s2 = new Student(1, "Rani", 22, "FeMale");

Constructor Overloading
-> Writing more than one constructor with different parameters is called as
Constructor Overloading

Example: class Employee {

Employee (int id){

Employee (double d){

InputStreamReader isr = new InputStreamReader ( );

BufferedReader br = new BufferedReader( isr );

String s = new String("hi");


StringBuffer sb = new StringBuffer(s);

Access Specifiers / Modifiers


-> These are used to specify accessibility for our classes, constructors, variables &
methods

-> In java we have below 4 access specifies / modifiers

1) public

2) private

3) protected

4) default

public: It is used to specify global access for classes, variables, methods and
Constructors

-> We can take class as public

-> We can take constructor as public

-> We can take variables as public

-> We can take methods as public

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't use private for classes (not allowed)

-> We can take variables as private

-> 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.

Class Name : EligServiceImpl

Method : public EligResponse executePlanCondtions(Long caseNum, String


planName, Integer age)

EligServiceImpl eligService = new EligServiceImpl ( );

EligResponse response = [Link] (. . .);


OOPS
Encapsulation: Combining variables & methods as single unit. It is used for data
hiding.

Ex: Java Class

Abstraction: Hiding un-necessary details and providing only useful information.

Ex: Abstract classes & Interfaces

Inheritance: The process of extending properties from one class to another class is
called as inheritance.

-> It is used for code re-usability

Polymorphism: Exhibiting multiple behaviours based on the situation is called as


Polymorphism.

Ex: Objects will exhibit multiple behaviours


Encapsulation
-> It is used for data hiding

-> We will combine variables & methods as one single unit using Class

-> Java class is one of the best example for Encapsulation

Example:

public class Account {

private int accNum;

private String name;

public void setAccNum(int accNum) {

[Link] = accNum;

public int getAccNum() {

return [Link];

public void setName(String name) {

[Link] = name;

public String getName() {

return [Link];

}
public class Test {

public static void main(String[] args) {

Account obj = new Account(); // obj creation

[Link](797979);

[Link]("Ashok");

int accNum = [Link]();

String name = [Link]();

[Link](accNum + "--" + name);

Inheritance
-> The process of extending the properties from one class to another class is called as
Inheritance

-> To extend the properties we will use 'extends' keyword

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

-> By using inheritance we can achieve code re-usability

Example:
class User {

// properties

// methods

class Student extends User {

Note: In above example 'User' class is acting as Parent class and Student class is
acting as Child class.

// Inheritance w.r.t to variables

public class User {

int id;

String name;

public class Student extends User {

int rank;

public static void main(String[] args) {

// child class object creation

Student s = new Student();

[Link] = 1;

// accessing parent class properties using child cls obj

[Link] = 101;

[Link] = "Bhanu";

[Link]([Link] + "--" + [Link] + "--" + [Link]);


}

public class Student extends User {

int rank;

public static void main(String[] args) {

// creating parent class obj

User user = new User();

[Link] = 101;

[Link] = "Raj";

[Link] = 1; // invalid bcz parent can't access child properties

// inheritance w.r.t to methods

public class User {

int id;

String name;

void m1() {

[Link](" Parent class :: m1 ( ) method called");

}
public class Employee extends User {

void m2() {

[Link]("Child class - m2() method called");

public static void main(String[] args) {

// creating object for child class

Employee emp = new Employee();

// calling parent class method

emp.m1();

// calling child class method

emp.m2();

// inheritance w.r.t to constructors

-> Whenever we create child class object, then first it will execute parent class zero-
param constructor and then it will execute child class constructor.

Q) Why Parent class constructor is executing first ?

-> 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() {

[Link]("Parent class :: 0-param constructor called ");

public class Employee extends User {

double salary;

public Employee() {

[Link]("Child Class :: 0-Param Constructor called");

void m2() {

[Link]("Child class - m2() method called");

public static void main(String[] args) {

// creating object for child class

Employee emp = new Employee();

// initializing parent class properties using child obj

[Link] = 101;

[Link] = "John";
// initialing child class properties using its own obj

[Link] = 4500.00;

[Link]([Link] + "--" + [Link] + "--" + [Link]);

Types of Inheritance
-> Inheritance is divided into multiple types

1) Single Level

2) Multi Level

3) Multiple --------> Not supported by Java due to Ambiguity problem

4) Hierarchical

Single level: Class B extends Class A

Multi-Level: Class C extends Class B extends class A extends Object

Multiple Inheritance: If one child having more than one parent (Java doesn't support
to avoid ambiguity)

Hierarchical: If one parent having multiple child’s

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() {

[Link]("Parent - Class - m1() Called");

void m2() {

[Link]("Parent - Class - m2() called");

class Child extends Parent {

public int hashCode() {

return 101;

void m1() {

[Link]("Child - Class - m1() Called");

void m2() {

[Link]("Child - Class - m2() called");

super.m2();

}
}

public class Test {

public static void main(String[] args) {

Child c = new Child();

c.m1();

c.m2();

int hashcode = [Link]();

[Link]("Hash Code :: " + hashcode);

Methods Execution Flow w.r.r to Inheritance


=> When we call a method using Object, first it will check in current class for that
method, if available it will call that method directly. If method not available in
current class then it will check in parent class (It can be direct or indirect parent). If
parent having that method then it will call parent class method. If parent class also
doesn't have method then it will throw Exception.

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

Phism ---> Forms

-> If any object is exhibiting multiple behaviours based on the Situation then it is
called as Polymorphism.

-> Polymorphism is divided into 2 types

1) Static polymorphism / Compile-time Polymorphism

Ex: Overloading

2) Dynamic polymorphism / Run-time Polymorphism

Ex: Overriding

Method Overloading
-> The process of writing more than one method with same name and different
parameters is called as Method Overloading.

public class Calculator {

void add (int i, int j) {

[Link]("Sum from 1st method :" + (i + j));

void add (int i, int j, int k) {

[Link]("Sum from 2nd method : " + (i + j + k));

public static void main(String[] args) {

Calculator c = new Calculator();


[Link](10, 20);

[Link](10, 20, 30);

[Link](10, 20, 30, 40); // invalid

=> When methods are performing same operation then we should give same name
hence it will improve code readability.

Ex:

substring (int start)

substring(int start, int end)

=> 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

public static void main (String ... args){

Child c = new Child ( );

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.

***************** Write a program on Method Overriding ******************

class RBIBank {

boolean checkElgibility() {

// docs verification logic

return true;

double getHomeLoanRofi() {

return 10.85;

}
public class SBIBank extends RBIBank {

// overriding parent method to give my own rofi

double getHomeLoanRofi() {

return 12.85;

public String applyHomeLoan() {

boolean status = checkElgibility(); // parent method

if (status) {

double homeLoanRofi = getHomeLoanRofi(); // child method

String msg = "Your loan approved with RI as ::" + homeLoanRofi;

return msg;

} else {

return "You are not elgible for home loan";

public static void main(String[] args) {

SBIBank bank = new SBIBank();

String msg = [Link]();

[Link](msg);

}
// Method Overriding Example with User-Defined Objects and String Objects

public class Demo {

public static void main(String[] args) {

SBIBank b1 = new SBIBank();

SBIBank b2 = new SBIBank();

boolean bankObjStatus = [Link](b2); // false

[Link]("Both Banks Are Equal ?? :: " + bankObjStatus);

String s1 = new String("ashokit");

String s2 = new String("ashokit");

boolean stringObjStatus = [Link](s2); // true

[Link]("Both Strings Are Equal ?? :: " + stringObjStatus);

Note: Object class equals ( ) method will compare address of the objects where String
class equals ( ) method will compare content of the objects.

Note: String class overriding equals ( ) method.


Types of Relations in Java Classes
-> In java classes we can use below 2 types of relations

1) IS-A relation -----> Inheritance

2) HAS-A relation -----> Composition

IS-A relation Example


-> If one class wants to re-use all the properties of another class then we will go for
IS-A relation.

Ex: Inheritance is the example for IS-A relation

class User {

int id;

String name;

void speak ( ){

[Link]("Hi, My Id is : "+ id + ", My Name : "+ name);

class Student extends User { // IS-A relation

public static void main(String... args){

Student s = new Student ( );

[Link] = 10;

[Link] = "Raju";

[Link] ( );

}
}

HAS-A Relation Example


-> If one class wants to re-use some properties of another class then we will go for
HAS-A relation.

Ex: Composition is the example for HAS-A relation

class Engine {

int id;

String name;

String fuelType;

void start ( ){

[Link]("Engine Starting....");

class Car {

void drive ( ){

Engine e = new Engine ( ); // HAS-A Relation

[Link] ( );

[Link]("Journey Started");

public static void main(String[] args){

Car c = new Car ( );


[Link] ( );

final keyword
-> final is a reserved keyword in java

-> We can use final keyword at 3 places

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.

public final int pi = 3.14;

pi = 4.32; // invalid

-> final methods can't overriden. We can't override final methods.


Abstraction
-> The process of hiding un-necessary data and providing only useful data is called as
Abstraction.

-> We can achieve abstraction using Interfaces & Abstract classes.

Method Types
-> In java we can write 2 types of methods

1) Concrete Method

2) Abstract Method

-> The method which contains body is called as 'Concrete method'

public void m1 ( ) {

-> The method which doesn't contain body is called as 'Abstract method'

public abstract void m2 ( ) ;

Note: By using 'abstract' keyword we can create abstract methods & abstract
classes.

Interfaces
-> Interfaces are used to achieve loosely coupling & abstraction

-> Interfaces contains only abstract methods (upto 1.7v of java)

-> To create a interface we will use 'interface' keyword

-> Interface doesn't contain 'constructor'

-> We can't create Object for the interface

-> Once interface is created then anybody can provide implementation for the
interface
-> Implementing interface means overriding 'interface abstract methods'

-> When we are implementing a interface then it is mandatory to implement all


abstract methods of that interface.

-> To implement a interface we will use 'implements' keyword

Note: One java class can implement Multiple Interfaces at a time.

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 void moneyTransfer();

public void checkBalance();

public class HdfcBank implements Bank {

public void moneyTransfer() {

[Link]("Money Transfer from HDFC....");

public void checkBalance() {

[Link]("Checking Balance from HDFC.....");

}
public class AxisBank implements Bank {

public void moneyTransfer() {

[Link]("Money Transfer from Axis ....");

public void checkBalance() {

[Link]("Check Balance from Axis....");

public class BankDemo {

public static void main(String[] args) {

Bank b; // reference variable

b = new AxisBank(); // storing impl obj into ref variable

[Link](); // axis-bank method will be called

[Link](); // axis-bank method will be called

b = new HdfcBank(); // storing impl obj into ref variable

[Link](); // hdfc-bank method will be called

[Link](); // hdfc-bank method will be called

}
=> We can't create Object for interface

=> Interface reference variable can hold its implementation class object.

Ex:

Bank b = new AxisBank ( ) ; // valid

Bank b = new HdfcBank ( ) ; // valid

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'

Ex: Cloneable, Serializable etc.....

-> 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.

// user defined marker interface


public interface Demo {

public class Test implements Demo {

Note: We can create our own marker interfaces but there is no use because JVM
don't know abt our marker interfaces.

Note: In java 1.8, they introduced Functional Interfaces.

-> The interface which contains only one abstract method is called as Functional
Interface.

-> Functional Interfaces are introduced to call 'Lambda Expressions'.

-> One interface can't implement another interface.

-> One Interface can extend another interface.

-> In Interface we can declare variables also, by default they are public static final.

public interface Bank {

public void checkBalance ( ) ;

public interface RbiBank implements Bank { // invalid

public interface RbiBank extends Bank { // valid

public void applyLoan ( ) ;

}
Abstract Classes
-> The class which contains both concrete and abstract methods is called as abstract
class.

-> We will use 'abstract' keyword to represent class as abstract class

-> To write abstract method 'abstract' keyword is mandatory

-> We can write constructor in abstract class but we can't create Object

-> Abstract classes can have child classes

-> 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.

abstract class DieselMachine {

public DieselMachine() {

[Link]("DieselMachine-Constructor");

public void start() {

[Link]("Machine starting....");

public abstract void fillFuel();

public class Machine extends DieselMachine {

public Machine() {

[Link]("Machine Constructor");

}
@Override

public void fillFuel() {

[Link]("filling fuel tank....");

public static void main(String[] args) {

Machine m = new Machine();

[Link]();

[Link]();

=> We can't use 'abstract' and 'final' combination because it is illegal.

public abstract final void m1 ( ) ; // invalid

=> abstract means override in child where as 'final' means don't override .
=> To create interface we will use 'interface' keyword

=> To create abstract classes we will use 'abstract' keyword

=> Interface contains abstract methods

=> Abstract classes can contain both abstract methods & concrete methods

=> Interface can't have constructor

=> Abstract class can have constructor

=> We can't create obj for interface

=> We can't create obj for abstract class

=> One interface can't implement another interface

=> One interface can extend another interface

=> 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

-> In java program we can write 2 types of blocks

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

-> Instance block will be executed before constructor execution

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

-> static block will execute before main ( ) method execution

syntax:

static

// stmts

}
Q) What is static control flow & instance control flow in java program ?

Static Control Flow


-> When class is loaded into JVM then static control flow will start

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


-> instance means Object

-> Instance control flow will begin when object is created for a class

-> When Object is created then memory will be allocated for

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

c) instance methods (if we call)

Note: static members can be access directly in instance areas because for static
members memory already allocated at the time of class loading.

public class Demo {

[Link]("i am from instance block");

public Demo() {

[Link]("I am from constructor");

static {

[Link]("I am from static block");

public static void main(String[] args) {

[Link]("i am from main method...");

Demo d = new Demo();

}
[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.

1) protected Object clone ( )

2) boolean equals (Object obj)

3) protected void finalize( )

4) Class <?> getClass( )

5) int hashCode( )

6) String toString( )

7) notify ( )

8) notifyAll ( )

9) void wait ( )

10) void wait(long timeout)

11) void wait (long timeout, int nanos)

Note: Last 5 methods will be used in Multi-Threading concept.


public String toString ( ) method :
-> It is used to represent Object in String format

-> When we print any object or when we call toString ( ) method by default it will call
Object class toString ( ) method

Object class toString( ) method implementation


public String toString ( ) {

return [Link]( ).getName ( ) + "@"+


[Link]([Link]());

Output: Student@15db9742

-> If we don't like this implementation, then we can override toString ( ) method in
our class like below

public class Student {

int id;

String name;

public static void main(String[] args) {

Student s = new Student();

[Link] = 101;

[Link] = "John";

[Link](s); // toString ( ) will be called

[Link]([Link]());
String s1 = new String("hi");

[Link](s1);

public String toString() {

return id + "--" + name;

-> We will override toString ( ) method to print content of object.

Note: String class is already overriding toString ( ) method.

int hashCode ( ) method


-> When we create object for a class then JVM will assign one unique hashcode for
every Object

-> Using hashCode ( ) method we can get hashcode of the object

-> If we don't want to execute Object class hashCode ( ) method then we can
override hashCode ( ) method in our class.

public class Student {

int id;

String name;

public static void main(String[] args) {

Student s = new Student();

[Link] = 101;

[Link] = "John";
[Link](s); // toString ( ) will be called

[Link]([Link]());

public String toString() {

return id + "--" + name;

public int hashCode() {

return id;

boolean equals ( Object obj ) method


-> equals ( ) method is used to compare one object with another object and returns
boolean value. If objects are same then it will return true otherwise it will return false
value.

Note: Object class equals( ) method will compare address of the object not content.

public class Student {

int id;

String name;

public Student(int id, String name) {

[Link] = id;

[Link] = name;

}
public static void main(String[] args) {

Student s1 = new Student(101, "John");

Student s2 = new Student(101, "John");

[Link]([Link](s2)); // false - compares address

[Link](s1 == s2); // false - compares address

String s3 = new String("hi");

String s4 = new String("hi");

[Link]([Link](s4)); // true - compares content of objects

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

public class Student {

int id;

String name;

public Student(int id, String name) {

[Link] = id;
[Link] = name;

public static void main(String[] args) {

Student s1 = new Student(101, "John");

Student s2 = new Student(101, "John");

[Link]([Link](s2)); // true - compares content (overriden)

[Link](s1 == s2); // false - compares address

String s3 = new String("hi");

String s4 = new String("hi");

[Link]([Link](s4)); // true - compares content of objects

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + id;

result = prime * result + ((name == null) ? 0 : [Link]());

return result;

}
@Override

public boolean equals(Object obj) {

if (this == obj) // s1 == s2

return true;

if (obj == null) // s2 == null

return false;

if (getClass() != [Link]())

return false;

Student other = (Student) obj; // typecasting

if (id != [Link]) // [Link] != [Link]

return false;

if (name == null) { // [Link] == null

if ([Link] != null)

return false;

} else if (![Link]([Link])) // ![Link]([Link])

return false;

return true; // ---> true

}
Class getClass ( ) method
-> This method is used to get Runtime instance of class

public class Student {

public static void main(String[] args) throws Exception {

Student s = new Student(); // obj creation

Class clz = [Link]();

[Link]([Link]());

[Link]([Link]().getName()); // method chaining to get cls


name

Object object = [Link](); //2nd approach to create object for a


cls

[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.

public class Student implements Cloneable {

public static void main(String[] args) throws Exception {


Student s = new Student();

[Link](s);

Object clone = [Link](); // cloning (another approch to create obj for a


class)

[Link](clone);

Q) In how many ways we can create Object for a class ?

Ans)

1) using new operator

2) using newInstance ( ) method

3) using clone ( ) method

finalize ( ) method
-> When garbage collector removing any object from JVM then it will call finalize ( )
method

Note: Garbage Collector is used to remove un-used objects / un-referenced objects


from JVM heap area.

finalize ( )

clone ( )

equals ( )

hashCode ( )

toString ( )
getClass ( )

notify ( )

notifyAll ( )

wait ( ) - 3 overloaded methods

class --> This is keyword to create class in Java

Class --> This is predefined class available in [Link] package

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)

2) Object Oriented Programming Language (OOP)

3) Classes

4) Objects

5) Variables (Instance, static & local)

6) Methods (Parameters & Return Type)

7) Instance methods & static methods

8) Constructors (default, 0-param constructor & parameterized constructor)

9) Constructor Overloading

10) this keyword

11) Access Modifiers (public, private, protected & default)

12) Encapsulation
13) setter methods & getter methods

14) Inheritence

15) Inheritence Types

16) Method Execution Order w.r.t Inheritence

17) Polymorphism

18) Method Overloading

19) Method Overriding

20) Concrete methods & abstract methods

21) Abstraction

22) Interfaces

23) Marker Interface

24) Abstract classes

25) Blocks

26) Static Control Flow

27) Instance Control Flow

28) Object class

29) Object class methods (11 methods)

30) final keyword

You might also like