Object Oriented Programming Concepts Using Java
Object Oriented Programming Concepts Using Java
Object Oriented Programming Concepts Using Java
using java
Oops Concepts
scope of variable
Wrapper classes
function overloding
function overriding
destructor
types of inheritance
types of polymorphism
It is similar to an if-else statement but they are defined inside another if-else statement.
Syntax:
if(condition1)
if(condition2){
Statement1;
else
stmt2;
else{
stmt3;
}
4. if-else-if Ladder
In this, the if statement is followed by multiple else-
if blocks. We can create a decision tree by using these
control statements in Java.
If the specified condition is true, then it execute the
statement. Otherwise execution moves onto else, in
else once again check the condition, if it is true then
execute the statement, otherwise execution moves on
to else.
If none of the conditions is true, the last else block is
executed(default statement)
Syn:
if(Cond1)
{
Stmt1;
}
else{
if(Cond2)
{
Stmt2;
}
else{
Stmt3;
}
}
5. switch
Statement
Switch statements are almost similar to the if-else-if ladder
control statements in Java. It is a multi-branch statement. It
is a bit easier than the if-else-if ladder and also more user-
friendly and readable.
We can use case values instead of conditions.
Note:
The expression can be of type String, short, byte, int, char,
We cannot have any duplicate case values.
The default statement is optional.
Usually, the break statement is used inside the switch to
terminate a statement sequence.
The break statement is optional.
Syntax:
switch(expression)
{
case value1:
Stmt1;
break:
case value2:
Stmt2;
break;
case value3:
Stmt3;
break;
default:
Stmtn;
}
Looping Statements in java
The java programming language provides a set of
iterative statements that are used to execute a
statement or a block of statements repeatedly as long as
the given condition is true.
The iterative statements are also known as looping
statements or repetitive statements.
• while statement
• do-while statement
• for statement
• for-each statement
while statement
The while statement is used to execute a single
statement or block of statements repeatedly as long as
the given condition is TRUE.
The while statement is also known as Entry control
looping statement.
Minimum number of execution of a statement in while
is -0.
It is also called pre-test loop. While entering into the
loop, it checks the condition.
do-while statement in java
The do-while statement is used to execute a single
statement or block of statements repeatedly as long as
given the condition is TRUE.
The do-while statement is also known as the Exit
control looping statement.
Minimum number of execution of a statement in do
while is-1
It is also called as post –test loop, i.e; while leaving
from the loop it checks the condition.
Most used loop by users.
for statement in java
The for statement is used to execute a single statement or a block of
statements repeatedly as long as the given condition is TRUE.
The Java for loop is the most powerful and versatile of iterative
statements.
Easy to implement.
Most commonly used loop.
In for-statement, the execution begins with
the initialization statement. After the initialization statement, it
executes Condition.
If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement.
After the block of statements execution, the modification statement
gets executed
For statement
Syntax:
for(initialization; condition; updation)
{
Statement;
}
in for statement initialization section executes into only once.
If we know the no of iterations well in advance then for loop is
the best choice.
1. Start
2. Create an instance of the Scanner class.
3. Declare a variable.
4. Ask the user to initialize it.
5. Perform the widening or automatic type conversion.
6. Print the value for each data type.
7. Stop.
import java.util.Scanner;
{
{
int i=sc.nextInt();
long l = i;
float f = l;
double d= f;
}
}
Java program to perform narrowing or explicite type conversion
in java.
Algorithm:
1. Start
2. Create an instance of the Scanner class.
3. Declare a variable.
4. Ask the user to initialize it.
5. Perform the narrowing or explicite type conversion.
6. Print the value for each data type.
7. Stop.
//Type Casting Program in Java
import java.util.Scanner;
{
{
double d=sc.nextDouble();
float f=(float)d;
long l = (long)d;
int i = (int)l;
}
}
Garbage collector in java
Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory
management.
The garbage collection is a part of the JVM and is an automatic process
done by JVM.
Garbage Collection can not be forced explicitly. We may request JVM
for garbage collection by calling System.gc() method.
Advantages of Garbage Collection
Programmer doesn't need to worry about dereferencing an object.
It is done automatically by JVM.
Increases memory efficiency and decreases the chances for memory
leak.
How can an object be unreferenced?
1. By nulling the reference
2. By assigning a reference to another
3. By anonymous object etc.
1.By nulling the reference.
set null to object reference which makes it able for garbage
collection.
For example:
CSE cs= new CSE();
cs=null; //which is ready for garbage collection.
2. CSE cs= new CSE();
CSE cs1= new CSE();
cs= cs1;
3. Anonymous object does not have any reference so if it is not in use, it is
ready for the garbage collection.
finalize() method
Sometime an object will need to perform some specific task before it is destroyed such as closing an
open connection or releasing any resources held. To handle such situation finalize() method is used.
The finalize() method is called by garbage collection thread(DAEMON THREAD) before collecting
object.
The gc() method is used to invoke the garbage collector to perform cleanup processing.
public class TestGarbage1{
public void finalize()
{System.out.println("object is garbage collected");
}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
} }
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects
and objects into primitives automatically.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with
objects many times like in Collections, Serialization, Synchronization, etc.
Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through
the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java.
The list of eight wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character …..etc.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
2nd way:
directly assign the values to an array.
int a[]= {1,2,3,4};
We can display the data from array by three ways.
by using index values.
by using for loop.
by using for each loop.
Array will be created with some specific blocks with default values first.
the default value is 0.
When we assign the values to array then default values are modified.
In java arrays are two types:
single dimensional
double dimensional.
}
}
String class in java
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string.
In java string represented by string class which is located in java.lang package.
It is probably the most commonly used class in java library.
string objects are immutable that means once a string object is created it
cannot be changed.
In Java, CharSequence Interface is used for representing a sequence of
characters. CharSequence interface is implemented by String, StringBuffer and
StringBuilder classes. This three classes can be used for creating strings in java.
The Java String is immutable which means it cannot be changed. Whenever we change
any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
the string doesn't exist in the pool, a new string instance is created and placed in the
pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Each time we create a String literal, the JVM checks the
string pool first. If the string literal already exists in the
pool, a reference to the pool instance is returned. If string
does not exist in the pool, a new string object is created,
and is placed in the pool. String objects are stored in a
special memory area known as string constant pool inside
the heap memory.
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variabl
e
String objects are immutable because:
class TestString
{
public static void main(String ar[]){
String s= new String("mahender");
s.concat("nagurla");
System.out.println(s);
}
}
o/p: mahender
StringBuffer class:
Java StringBuffer class is used to create mutable (modifiable) String
objects. The StringBuffer class in Java is the same as String class
except it is mutable i.e. it can be changed.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
charAt() Returns the character at the specified index (position) char
equals() Compares two strings. Returns true if the strings are boolean
equal, and false if not
5. Static variables:
If you declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
• The static variable gets memory only once in the class area at the time of class
loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
1. class Student{
2. int rollno;
3. String name;
4. String college=“SRU";
5. }
Suppose there are 3000 students in my college, now all instance data members
will get memory each time when the object is created.
All students have its unique rollno and name, so instance data member is good
in such case. Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.
When we have a class variable like this, defined using the static keyword, then the
variable is defined only once and is used by all the instances of the class.
name
obj1 Rollno
rollno
obj2 name
rno
name
heap
class Employee
{
int eid;
String name;
static String company = "SRU";
public void show()
{
System.out.println(eid + "-" + name + "-" + company);
}
public static void main( String[] args )
{
Employee se1 = new Employee();
se1.eid = 104;
se1.name = "Abhijit";
se1.show();
Employee se2 = new Employee();
se2.eid = 108;
se2.name = "ankit";
se2.show();
}
Static methods in java
Any method that uses the static keyword is referred to as a
static method.
If the keyword static is prefixed before the method name, the
function is called a static method.
you can call a static method without creating an object of the
class. Static methods are sometimes called class methods.
Static methods do not need instance of its class for being
accessed.
main() method is the most common example of static method.
main() method is declared as static because it is called before
any object of the class is created.
Properties of Static Function
It can access only static members.
It can be called without an instance.
It is not associated with the object.
Non-static data members cannot be accessed by the static function.
Syntax:
1. [access specifier] static [return type] [function name] (parameter list)
2. {
3. //body of the function
4. }
Calling Static Function
In Java, we cannot call the static function by using the object. It is invoked by
using the class name.
1. [class name].[method name]
import java.io.*;
class StaticMethodExample1 {
static int a = 40;
int b = 50;
void simpleDisplay()
{
System.out.println(a);
System.out.println(b);
}
static void staticDisplay()
{
System.out.println(a);
}}
class StaticMethodExample{
public static void main(String[] args) {
StaticMethodExample1 obj = new StaticMethodExample1();
obj.simpleDisplay();
StaticMethodExample1.staticDisplay();
}}
A constructor is a special method that is used to initialize an object.
Every class has a constructor either implicitly or explicitly.
It is called when an instance of the class is created. At the time of
calling the constructor, memory for the object is allocated in the
memory.
Every time an object is created using the new() keyword, at least one
constructor is called.
constructor is a method that is called at runtime during the object
creation by using the new operator.
The JVM calls it automatically when we create an object. When we
do not define a constructor in the class, the default constructor is
always invisibly present in the class.
In short, we use the constructor to initialize the instance variable of
the class.
We use constructors to initialize the object with the default or initial
state. The default values for primitives may not be what are you
looking for.
Rules for creating Java constructor
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
class classname
{
<class-name>( ) // constructor
{
code statements;
}
Types of Constructor
Java Supports two types of constructors:
• Default Constructor
• Parameterized constructor
Default Constructor
In Java, a constructor is said to be default constructor if it does
not have any parameter. Default constructor can be either user
defined or provided by JVM.
If a class does not contain any constructor then during runtime
JVM generates a default constructor which is known as system
define default constructor.
Syntax:
class classname {
<class-name>( ) // constructor
{
code statements; }
Example:
class CSE {
CSE( ) // default constructor
{
} }
class ConstructorDemo {
public static void main(String ar[]) {
System.out.println("hi");
} }
Java Program on Default Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.
A constructor that has parameters is known as parameterized constructor.
If we want to initialize fields of the class with our own values, then use a
parameterized constructor.
Syntax:
class classname
{
<class-name>( parameters list) // parameterized constructor
{
code statements;
}
Copy Constructor
In Java, a copy constructor is a special type of constructor that
creates an object using another object of the same Java class. It
returns a duplicate copy of an existing object of the class.
It cannot be inherited by the subclasses. If we try to initialize a
child class object from a parent class reference, we face the casting
problem when cloning it with the copy constructor.
• If a field declared as final, the copy constructor can change it.
• There is no need for typecasting.
Avoid the use of the Object.clone() method.
If we are using the clone() method it is necessary to import
the Cloneable The method may throw the
exception CloneNotSupportException. So, handling the exception
in a program is a complex task. While in copy constructor there are
no such complexities.
Method overloading is a concept that allows to declare multiple
methods with same name but different parameters in the same
class.
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
Method overloading increases the readability of the program.
Method overloading in Java is also known as Compile-time
Polymorphism, Static Polymorphism, or Early binding.
Different Ways of Method Overloading in Java
1. Changing the Number of Parameters.
2. Changing Data Types of the Arguments.
3. Changing the Order of the Parameters of Methods
Example:
class CSE
{
void display(int a, int b)
{
}
void display(int a, int b, int c) // no of parameters changed
{
}
void display(int a, float f) // type of parameters changed
{ }
void display(int b, float a) // order of parameters changed
{
}
}
Java program on methodoverloading
One type is promoted to another implicitly if no matching datatype is found.
As displayed in the below diagram, byte can be promoted to short, int, long, float
or double. The short datatype can be promoted to int, long, float or double. The
char datatype can be promoted to int,long,float or double and so on.
Short
Byte
Char
In Java, we can overload constructors like methods.
The constructor overloading can be defined as the concept of having more
than one constructor with different parameters so that every constructor
can perform a different task.
Overloaded constructors are differentiated on the basis of their type of
parameters or number of parameters.
When we create an object to class JVM creates a default constructor to a
class to initialize the instance variables with default values.
Constructor Chaining
Constructor chaining is a process of calling one constructor from another
constructor in the same class. Since constructor can only be called from
another constructor, constructor chaining is used for this purpose.
To call constructor from another constructor this keyword is used. This
keyword is used to refer current object.
In Java, when we create an object of the class it occupies some space in
the memory (heap). If we do not delete these objects, it remains in the
memory
To resolve this problem, we use the destructor.
The destructor is the opposite of the constructor. The constructor is used
to initialize objects while the destructor is used to delete or destroy the
object that releases the resource occupied by the object.
there is no concept of destructor in Java. In place of the destructor, Java
provides the garbage collector that works the same as the destructor.
When an object completes its life-cycle the garbage collector deletes
that object and deallocates or releases the memory occupied by the
object.
The Java Object class provides the finalize() method that works the same
as the destructor.
Inheritance is one of the key features of Object Oriented Programming.
Inheritance provided mechanism that allowed a class to inherit property of
another class. When a Class extends another class it inherits all non-private
members including fields and methods.
We can create a new class from existing class.
Acquiring the properties from one class to another class.
Inheritance defines is-a relationship between a Super class and its Sub class.
extends and implements keywords are used to describe inheritance in Java.
• Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
Advantages of Inheritance:
1. It promotes the code reusabilty i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.
Main disadvantage of using inheritance is that the two classes (parent and
child class) gets tightly coupled. This means that if we change code of parent
class, it will affect to all the child classes which is inheriting/deriving the parent
class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
In inheritance We always create the object to subclass. With this, we can access
the data members from sub class and its super class.
Types of Inheritance
Java mainly supports only four types of inheritance that are listed below.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance:(It is not achieved directly but possible through
interface)
BTECH
1.Single Inheritance:
When a class extends to another class then it forms single inheritance.
One class is inherited from only one super class
In single inheritance only one super class and only one sub class CSE
Multilevel Inheritance:
When a class extends to another class that also extends some other class forms a
multilevel inheritance.
In multi level inheritance, we have one Super class, one sub class along with
intermediate classes.
Here Intermediate classes act as Super class and sub class based on situation.
Syntax;
A
Class A //super class
{
}
class B extends A //sub class/
B
super class
{
}
class C extends B //sub class
{ C
}
Hierarchical Inheritance:
When two or more classes inherits a single class, it is
known as hierarchical inheritance.
In this inheritance, we can create two or more new classes
from a single super class.
Syntax:
class A A
{
}
class B extends A
{
B C
}
class C extends A
{
}
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
Method overriding is a process of overriding base class method by derived class
method with more specific definition.
It is performed between two classes using inheritance relation.
Method overriding performs only if two classes have is-a relationship.(inheritance)
Method overriding is also referred to as runtime polymorphism because calling
method is decided by JVM during runtime.
Rules for Method Overriding
1. Method name must be same for both parent and child classes.
2. Private, final and static methods cannot be overridden.
3. There must be an IS-A relationship between classes (inheritance).
class Eamcet {
protected void displayInfo() {
System.out.println("Iam aspirant of Eamcet");
}
}
class MethodOverriding {
public static void main(String[] args) {
Btech d1 = new Btech();
d1.displayInfo();
}
}
In Java, this is a keyword which is used to refer current
object of a class. we can it to refer any member of the class. It
means we can access any instance variable and method by
using this keyword.
The main purpose of using this keyword is to solve the
confusion when we have same variable name for instance and
local variables.
We can use this keyword for the following purpose.
• this keyword is used to refer to current object.
• this is always a reference to the object on which method was
invoked.
• this can be used to invoke current class constructor.
this: to refer current class instance
1. variable
class Student{
2. int rollno;
3. String name;
4. Student(int rollno,String name) {
5. this.rollno=rollno;
6. this.name=name;
7. }
this: to invoke current class method
1. class A{
2. void show(){
3. System.out.println("hello m"); }
4. void display(){
5. System.out.println("hello n");
this.show();
1. } }
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
• super variable refers immediate parent class instance.
• super variable can invoke immediate parent class method.
• super() acts as immediate parent class constructor and should be first line in child
class constructor.
Abstraction is the concept of object-oriented programming that “shows”
only essential attributes and “hides” unnecessary information.
The main purpose of abstraction is hiding the unnecessary details from the
users.
A class which is declared using abstract keyword known as abstract class.
An abstract class may or may not have abstract methods.
We cannot create object of abstract class.
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
An abstract class is a class that contains at least one abstract method.
Abstract class can have concreate methods and abstract methods.
Syntax:
abstract class class_name
{
code of a class:
}
Example: