Java OOPS
Java OOPS
This approach is very close to the real-world because the state and behavior of these classes and objects are almost the
same as real-world entities. OOP programming languages: C++ and JAVA.
AIM : "Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in
programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other
part of the code can access this data except that function ."
Note: Object-based programming approach is the approach which primarily supports only few OOP concepts like data
encapsulation , data hiding, function overloading and objects. This approach don't implement inheritance and dynamic
binding. Eg of OBP language : Ada programming language.
Thus Object Oriented Programming = Object based Programming + Inheritance + Dynamic Binding.
Note: Purely Object Oriented Programming languages are those languages in which everything accessible(both
predefined types and user defined types and even functions) are objects. Languages like C++ and Java are thus not pure
OOP languages because they have primitive data types like int , double which are not objects. Example of Pure OOP
languages are python, ruby, dart. Etc.
Key Points
1. OOP treats data as a critical element.
2. Emphasis is on data rather than procedure.
3. Decomposition of the problem into simpler modules.
4. Doesn’t allow data to freely flow in the entire system, i.e. localized control flow.
5. Programs are divided into classes and their objects.
6. Data is hidden/protected from external functions.
7. Objects may communicate with each other by functions.
8. It is an Bottom Up Approach. A bottom-up approach begins with low level design or development and ends with high
level design.
Advantages of OOP
• Real World Model & Applications: It models the real world very well.
• Maintainability: With OOP, programs are easy to test, debug, understand and maintain , thus complex software
Java Page 1
• Maintainability: With OOP, programs are easy to test, debug, understand and maintain , thus complex software
programs are easy to manage.
• Data Security: Principle of Data Hiding helps to build secure programs that cannot be invaded by code in other parts
of programs.
• Reusability: OOP offers code reusability. Already created classes or their features can be reused using inheritance
without having to write them again.
• Fast Development: OOP facilitates the quick development of programs where parallel development of classes and
partition of work is possible and thus higher productivity.
• Scalability: Object Oriented Systems can be easily upgraded from small to large systems.
Disadvantages of OOP
1. Larger program size: Object-oriented programs typically involve more lines of code than procedural programs.
2. Slower programs: Object-oriented programs are typically slower than procedurebased programs, as they typically
require more instructions to be executed.
3. Complex Programs and High Skills: It is very complex to create programs based on the interaction of objects. Some of
the key programming techniques, such as inheritance and polymorphism, can be a big challenging to comprehend
initially.
Applications of OOP
• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and expertext
• Al and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems
Basis Main focus is on the procedure or Main focus is on 'data security'. Hence, only objects are
structure of a program . permitted to access the entities of a class.
Division Large program is divided into units Entire program is divided into objects.
called functions.
Entity accessing No access specifier observed. Access specifier are "public", "private", "protected".
mode
Java Page 2
mode
Overloading or Neither it overload functions nor It overloads functions, constructors, and operators.
Polymorphism operators.
Data hiding & There is no proper way of hiding the Data is hidden in three modes public, private, and
security data, so data is insecure protected, hence data security increases.
Data sharing Global data is shared among the Data is shared among the objects through the member
functions in the program. functions.
Abstract Class & No concept of abstract classes or Abstract Classes & Interface available in Java, (pure virtual
Interface interface. function in C++).
Java Page 3
Class & Object
Class
"Class is an user-defined data type, which holds its own data members (or instance variables) and member functions (or methods), which can be
accessed and used by creating an instance of that class."
A class is like a blueprint for an object. The primary purpose of the class is to store data and information. Data members & member functions of a class
define the properties & behavior of the objects in a class.
Note: "Memory space for objects is allocated when they are declared and not when class is specified".
This statement is only partly true. Actually, the member functions are created and placed in the memory space only once when they are defined as a
part of class specification. Thus only space for data members is allocated separately every time object is declared (and memory for code of member
functions gets already allocated only once for one class).
Object
" An Object is an identifiable entity with some characteristics and behavior. An Object is an instance of a Class. When a cla ss is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is allocated."
A class is the blueprint of the object, but also, we can say the implementation of the class is the object. The class is not visible to the world, but the
object is.
Java Page 4
3. Initializing reference with the object.
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes
the class constructor.
objectName is just a reference to the object memory in heap, not the actual object itself (unlike primitive datatype). Naming convention for object is
same as naming convention for any variable.
ClassName should start with a capital letter(according to the naming conventions). Example) System, String, Integer, etc.
In Java, memory for an object is always allocated on heap. Only primitive datatypes (int, boolean, char, float, double, etc) are allocated space on stack
memory. Only the reference to the object, which holds the address of the actual object, is stored in stack memory.
Example:
class Outer {
int outerVar = 5;
class Inner {
int innerVar = 10;
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
}
}
Note: We can’t have static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot
define any static method for itself.
Example:
class Outer {
void outerMethod() {
class Inner {…}
Inner y = new Inner();
Java Page 5
Inner y = new Inner();
}
}
class Main{
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}
Note: Method Local inner classes can’t use local variable of outer method until that local variable is not declared as final. The main reason we need
to declare a local variable as a final is that local variable lives on stack till method is on the stack but there might be a case the object of inner class
still lives on the heap.
It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways:
a. Interface
Example:
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Example:
class Outer {
private static void outerMethod() {
System.out.println("inside outerMethod");
}
Java Page 6
}
}
Java Page 7
Constructor
A constructor is a special method for every class, which is used to construct the values of instance variables at the time of object creation. It
is called when an object instance of the class is created. At the time of calling constructor, memory for the object is allocated in the heap
memory.
Every time an object is created using the new keyword, a constructor is called. It calls a default constructor (no-arg constructor) if there is no
constructor available in the class. In such case, Java compiler provides a default constructor by default. It is not necessary to write a
constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
Constructor Overloading
• In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
• Constructor overloading is a technique of having more than one constructor with different parameter lists.
• They are arranged in a way that each constructor performs a different task.
• They are differentiated by the compiler by the number of parameters in the list and their types.
Types of Constructors
There are three types of constructors in Java:
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public int students;
public Pepcoding()
{ students = 0; }
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding();
// Calling Custom Default Constructor
Java Page 8
// Calling Custom Default Constructor
System.out.println(obj.students);
}
}
2. Parameterized constructor
A constructor which has a specific number of parameters is called a parameterized constructor. The parameterized constructor is used
to provide different values to distinct objects. However, you can provide the same values also.
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public int students;
public Pepcoding(int students)
{ this.students = students; }
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding(50);
// Calling Parameterized Constructor
System.out.println(obj.students);
}
}
3. Copy constructor
A copy constructor is a special type of parameterized constructor where there is only one argument in the argument list, which is of the
type of same class only. It is used to copy the values from another object (argument) into the current object (this).
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public int students;
public Pepcoding(int students)
{ this.students = students; }
public Pepcoding(Pepcoding obj)
{ this.students = obj.students; }
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding(50);
// Calling Parameterized Constructor
Java Page 9
System.out.println(copy.students);
}
}
Very Important Note: If the programmer provides atleast one custom constructor in the class, whether it is default or parameterized,
compiler will not create it's own default constructor in that case.
Hence, if we are defining a parameterized constructor, then it is a good practice to also define a default constructor, otherwise, there will
be no constructor available with 0 arguments.
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public int students;
public Pepcoding(int students)
{ this.students = students; }
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding();
// Trying to Call Default Constructor, but the constructor provided by Compiler
// will not be created since, there is a parameterized constructor.
// It will give: Constructor Undefined Exception
System.out.println(copy.students);
}
}
Java Page 10
this keyword
In Java, this is a reference variable that refers to the current object.
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public String student;
public int rollNo;
Pepcoding(String student, int rollNo){
student = student;
rollNo = rollNo;
}
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding("Ram", 25);
System.out.println(obj.student + ',' + obj.rollNo);
}
}
It will print null, 0. To resolve the ambiguity, we can modify the constructor by using this keyword:
import java.lang.*;
import java.util.*;
class Pepcoding{
public String student;
public int rollNo;
Pepcoding(String student, int rollNo){
this.student = student;
this.rollNo = rollNo;
}
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding("Ram", 25);
System.out.println(obj.student + ',' + obj.rollNo);
}
}
• this can be used to invoke current class method or constructor (implicitly). If you don't use the this keyword, compiler automatically adds this
keyword while invoking the method.
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public String student;
public int rollNo;
Pepcoding(String student, int rollNo){
this.setRollNo(rollNo);
this.setStudent(student);
}
void setStudent(String student)
{
this.student = student;
}
Java Page 11
}
void setRollNo(int rollNo)
{
this.rollNo = rollNo;
}
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding("Ram", 25);
System.out.println(obj.student + ',' + obj.rollNo);
}
}
• this() can be used to invoke current class constructor. It can be used in constructor chaining. For Eg, it can be used to call parameterized
constructor from default constructor.
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public int rollNo;
Pepcoding()
{ this(1); }
Pepcoding(int rollNo)
{
this.rollNo = rollNo;
}
}
class Program{
public static void main(String args[])
{
Pepcoding obj = new Pepcoding();
System.out.println(obj.rollNo);
}
}
Java Page 12
static keyword
static keyword is used for memory management in Java. The static keyword belongs to the class itself rather than an instance of the class.
The static keywords can be applied to instance variables, methods, a section/block of code in class, or nested class.
Static variable
• The static variable can be used to refer to the common property of all objects (which is not unique for each object).
• Hence, all instances (objects) of the class share the same static variable.
• The static variable gets memory only once in the class area at the time of class loading by JVM.
• Advantages of static variable is that it makes your program memory efficient (i.e., it saves memory).
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public static int students = 50;
}
class Program{
public static void main(String args[])
{
Pepcoding obj1 = new Pepcoding();
Pepcoding obj2 = new Pepcoding();
System.out.println(Pepcoding.students);
System.out.println(obj1.students);
System.out.println(obj2.students);
}
}
All three print statements will give 50, as all instances will share same students variable. Also, we can access the static variable using dot (.)
operator on class itself.
Static method
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public static int students = 50;
public static int calcBatches()
{ return students/10; }
}
class Program{
public static void main(String args[])
{
Pepcoding obj1 = new Pepcoding();
Pepcoding obj2 = new Pepcoding();
System.out.println(Pepcoding.calcBatches());
System.out.println(obj1.calcBatches());
System.out.println(obj2.calcBatches());
}
}
Static block
• Is used to initialize the static data members and data members marked as final.
• It is executed before the main method at the time of class loading.
Example:
import java.lang.*;
import java.util.*;
class Pepcoding{
public static final int students;
Java Page 13
public static final int students;
static{
students = 50;
}
}
class Program{
public static void main(String args[])
{
Pepcoding obj1 = new Pepcoding();
Pepcoding obj2 = new Pepcoding();
System.out.println(Pepcoding.students);
System.out.println(obj1.students);
System.out.println(obj2.students);
}
}
Java Page 14
Inheritance
"The capability of a class (child class) to derive properties and characteristics from another class (parent class) is called Inheritance."
When we create a class, we do not need to write all the properties and functions again and again, as these can be inherited from another class which
possesses it. Inheritance allows the user to reuse the code whenever possible and reduce its redundancy.
Real world example of inheritance can be humans. We inherit certain properties from the class ‘Human’ such as the ability to speak, breathe, eat, drink,
etc.
We can also take the example of cars. The class ‘Car’ inherits its properties from the class ‘Automobiles’ which inherits some of its properties from
another class ‘Vehicles’.
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the
functionality.
1. Single Level Inheritance: When a class inherits another class, it is known as a single inheritance.
Example: Pepcoder IS-A Programmer. Hence, class Pepcoder can extend class Programmer, with some extra functionality like batch details,
attendance, etc.
import java.lang.*;
import java.util.*;
class Programmer{
public String language = "Java";
}
class Pepcoder extends Programmer{
public String batch = "NADOS1";
};
class Program{
Java Page 15
class Program{
public static void main(String args[])
{
Pepcoder obj = new Pepcoder();
System.out.println(obj.language);
System.out.println(obj.batch);
}
}
import java.lang.*;
import java.util.*;
class Programmer{
public String language = "Java";
}
class Pepcoder extends Programmer{
public String batch = "JSP1";
};
class TeachingAssistant extends Pepcoder{
public int doubtsTaken = 0;
TeachingAssistant(int doubtsTaken)
{ this.doubtsTaken = doubtsTaken; }
};
class Program{
public static void main(String args[])
{
TeachingAssistant obj = new TeachingAssistant(20);
System.out.println(obj.language);
System.out.println(obj.batch);
System.out.println(obj.doubtsTaken);
}
}
3. Hierarchial Inheritance: When two or more classes inherits a single class, it is known as hierarchical inheritance.
Example: Animal can extended by Dog, Cat, Horse, etc.
import java.lang.*;
import java.util.*;
class Animal{
public int size = 100;
}
class Dog extends Animal{
void bark() {System.out.println("Barking.."); }
};
class Cat extends Animal{
void meow() {System.out.println("Meow.."); }
};
class Program{
public static void main(String args[])
{
Dog myDog = new Dog();
Cat myCat = new Cat();
System.out.println(myDog.size);
myDog.bark();
System.out.println(myCat.size);
myCat.meow();
}
}
Note: Java does not support Multiple inheritance. However, there is a workaround to acieve similar functionality, using the power of Interfaces. Hence,
in Java, one class is allowed to extend only one parent class. There cannot be more than one super classes of a sub class. Hence, inheritance of following
kinds is not possible in Java(it is not allowed intentionally to avoid the Deadly Diamond of Death Problem):
Java Page 16
Constructors in Inheritance
Order of execution of constructors in multilevel inheritance is always from topmost class (superclass) to the bottom-most class (childclass). Please note
that, even if we make an object of child class using new keyword, i.e. even if we call constructor of derived class first, this derived class constructor itself
calls the base class constructor, in the first statement implicitly.
Hence, though first constructor called is of derived class, first constructor executed is of base class. This concept can be understood by the help of an
example of building of a construction. Always, first, the foundation is laid, i.e. the base is created, then only the sky-touching floors are constructed. You
cannot directly construct the floors on top without building all the floors below it.
If we want to pass arguments to base class constructor, i.e. call parameterized constructor of base class, then we can write super(argument list); as the
first statement in the child class constructor. This will tell the compiler, that programmer have explicitly mentioned, which base class constructor to be
called. If this statement is not written, then compiler always add super(); statement impliclty, thereby calling the default constructor of base class. Also,
please remember that the super(); statement should be the first statement inside the constructor body. There must be no statement before it.
super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.
2. super can be used to invoke immediate parent class method. It should be used if subclass contains the same method as parent c lass. In other words,
it is used if method is overridden.
Example:
import java.lang.*;
import java.util.*;
class Animal{
String color = "Red";
void getColor() {System.out.println(this.color); }
}
class Dog extends Animal{
String color = "Red";
void getColor() { super.getColor(); }
};
class Program{
public static void main(String args[])
{
Dog myDog = new Dog();
myDog.getColor();
}
}
Java Page 17
}
};
class Program{
public static void main(String args[])
{
Dog myDog = new Dog();
System.out.println(myDog.color);
}
}
Java Compiler provides super() call in the constructor of subclass, implicitly, to call for the constructor of super class (constructor chaining), if not done
explicitly by the programmer.
Important Note: Call to super(); must be the first statement of the subclass constructor. We cannot write any statement before calling super().
Java Page 18
Polymorphism
"The word polymorphism means having many forms. polymorphism is the ability of a message to be displayed in more than one form."
Polymorphism is the ability of data to be processed in more than one form. It allows the performance of the same task in various ways. It
consists of method overloading and method overriding, i.e., writing the method once and performing a number of tasks using the same method
name.
Real world example of polymorphism can be a girl. She can be a daughter, mother, sister and and in all a human being.
Another example can be a mobile phone. The same mobile phone is used to take calls, click pictures & videos, run calculator and other
applications, etc.
Advantages of Polymorphism:
• It helps the programmer to reuse the codes, i.e., classes once written, tested and implemented can be reused as required. Saves a lot of
time.
• Single variable can be used to store multiple data types.
• Easy to debug the codes.
Disadvantages of Polymorphism:
• Run time polymorphism can lead to the performance issue as machine needs to decide which method or variable to invoke so it basically
degrades the performances as decisions are taken at run time.
• Polymorphism reduces the readability of the program. One needs to identify the runtime behavior of the program to identify actual
execution time.
Polymorphism is extensively used in implementing inheritance. An operation may exhibit different behaviors in different instances. The
behavior depends upon the types of data used in the operation. Polymorphism can be implemented using Method Overloading and Method
Overriding.
Method Overloading
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only
one operation, having same name of the methods increases the readability of the program.
Method overloading is a technique to implement compile-time polymorphism in Java. A call invocation is binded with appropriate method at
the compile-time only. This kind of method binding is known as static binding.
Example) Overloading addition method to handle addition of two integers versus two doubles, we can use same function name, thus improving
readibility.
Note: Method Overloading is not possible by changing the return type of the method only. Hence, two methods with same argument list, but
different return type are not overloaded methods. Hence, writing such methods in same class will lead to ambiguity, thus method redefined
compile-time error will be displayed.
Example:
int add(int a, int b){return a+b;}
long add(int a, int b) {return a+b;}
It will lead to add method redefined error, as both methods have exactly same argument list, but just different return type.
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a
subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method
Java Page 19
subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method
overriding. Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. Method
overriding can be used to implement run-time polymorphism by using the concept of dynamic/run-time binding.
Example:
import java.lang.*;
import java.util.*;
class Animal{
void eat() { System.out.println("Eating"); }
}
class Dog extends Animal{
void eat() { System.out.println("Eating Dog Food"); }
};
class Program{
public static void main(String args[])
{
Dog myDog = new Dog();
myDog.eat();
}
}
It will print "Eating Dog Food" as overrided method eat() of class Dog will be called.
Note: We cannot override static methods because the static method is bound with class whereas instance method is bound with an object.
Static belongs to the class area, and an instance belongs to the heap area. Due to this reason, main method cannot be overrided.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable.
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. Note that, parent need not be class, it can be
interface also.
Example
class A{}
class B extends A{}
A a=new B();//upcasting
Java Page 20
method is invoked at runtime. Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
import java.lang.*;
import java.util.*;
class Car{
void run()
{ System.out.println("running"); }
}
class Alto extends Car{
void run()
{ System.out.println("run at maximum 100kmph"); }
}
class Program{
public static void main(String args[])
{
Car b = new Alto();//upcasting
b.run(); // Run Time Polymorphism or Dynamic Method Dispatch
}
}
Java Page 21
final keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in many context:
1. Final Variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example:
import java.lang.*;
import java.util.*;
class MyScience{
public static final long speedOfLight = 3e8;
}
class Program{
public static void main(String args[])
{
System.out.println(MyScience.speedOfLight);
}
}
2. Final Method
If you make any method as final, you cannot override it. (Final method can be inherited, but not overrided).
Example:
import java.lang.*;
import java.util.*;
class MyMath{
public long radius = 10;
public final double getArea()
{
return Math.PI * radius * radius;
}
}
class Program{
public static void main(String args[])
{
MyMath obj = new MyMath();
System.out.println(obj.getArea());
}
}
3. Final Class
A final class cannot be extended(inherited). Hence, final class is used to prevent inheritance. For example, all Wrapper Classes like
Integer,Float etc. are final classes. We can not extend them.
Example:
import java.lang.*;
import java.util.*;
final class MyMath{
public long radius = 10;
public final double getArea()
{
return Math.PI * radius * radius;
}
}
class Program{
public static void main(String args[])
{
MyMath obj = new MyMath();
System.out.println(obj.getArea());
}
}
Java Page 22
Data Abstraction
"Data abstraction refers to providing only essential information about the data to the outside world, hiding the background
details or implementation."
Abstraction refers to the act of representing important and special features without including the background details or
explanation about that feature. Data abstraction simplifies database design. Since classes implement Data Abstraction, hence
classes are called ABSTRACT DATATYPE (ADT).
a. Physical Level:
It describes how the records are stored, which are often hidden from the user. It can be described with the
phrase, “block of storage.”
b. Logical Level:
It describes data stored in the database and the relationships between the data. The programmers generally
work at this level as they are aware of the functions needed to maintain the relationships between the data.
c. View Level:
Application programs hide details of data types and information for security purposes. This level is generally
implemented with the help of GUI, and details that are meant for the user are shown.
Real world example of Data Abstraction is ATM Machine: All are performing operations on the ATM machine like cash
withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM.
Abstraction in Java
In Java, abstraction is mainly achieved using abstract classes and interfaces.
Abstract Class
• An abstract class is a class that is declared with abstract keyword. Any class that contains one or more abstract methods
must also be declared with abstract keyword.
• An abstract method is a method that is declared without implementation. An abstract class may or may not have all abstract
methods. Some of them can be concrete methods
• A method defined abstract must always be redefined in the subclass, thus making overriding compulsory. If we do not
override abstract methods in subclass, then the subclass will also become abstract.
• There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new
operator.
• An abstract class can have parameterized constructors and default constructor is always present in an abstract class.
• Abstract classes are made to achieve generalization. For eg, if we want to create a super class Animals for all the animal
Java Page 23
• Abstract classes are made to achieve generalization. For eg, if we want to create a super class Animals for all the animal
types like dog, cat, etc. then we can make animal as abstract, because Animal itself is not a real world entity. Hence, we do
not need any objects of class Animal.
Example:
import java.lang.*;
import java.util.*;
abstract class Animal{
String color;
Animal(String color)
{ this.color = color; }
public abstract void makeSound();
}
class Dog extends Animal{
Dog(String color)
{ super(color); }
@Override
public void makeSound()
{ System.out.println("Woof Woof .. "); }
}
class Cat extends Animal{
Cat(String color)
{ super(color); }
@Override
public void makeSound()
{ System.out.println("Meow Meow .. "); }
}
class Program{
public static void main(String args[])
{
Cat myCat = new Cat("Black");
myCat.makeSound();
Dog myDog = new Dog("White");
myDog.makeSound();
}
}
Interfaces
• Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract
(only method signature, no body).
• All methods in an interface are abstract. Hence, interface acts as an abstract class with no concrete method.
• Interfaces specify what a class must do and not how. It is the blueprint of the class. So it specifies a set of methods that the
class has to implement.
• If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the
class must be declared abstract.
• There are many interfaces present in Java Collections framework like Queue Interface, Comparator Interface, etc.
• To implement interface use implements keyword, instead of extends in inheritance. Apart from total abstraction, interfaces
is also used to achieve behavior similar to multiple inheritance, as more than one interfaces can be implemented in java, but
more than one classes cannot be extended.
Example:
Consider interface Shape. We can implement Shape in different concrete classes like Rectangle, Circle, Triangle, etc.
import java.lang.*;
import java.util.*;
Java Page 24
import java.util.*;
interface Shape
{
void input(int param);
void area();
}
class Circle implements Shape
{
int radius = 0;
final double PI = 3.14;
@Override
public void input(int radius)
{
this.radius = radius;
}
@Override
public void area()
{
double area = PI * radius * radius;
System.out.println("Area of circle : " + area);
}
}
class Square implements Shape
{
int side = 0;
public void input(int side)
{
this.side = side;
}
public void area()
{
double area = side * side;
System.out.println("Area of Square : " + area);
}
}
class Program{
public static void main(String args[])
{
Square obj = new Square();
obj.input(5); obj.area();
Circle obj2 = new Circle();
obj2.input(5); obj2.area();
}
}
Java Page 25
variables.
The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.
An abstract class can be extended using keyword "extends". An interface can be implemented using keyword
"implements".
A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
Java Page 26
Encapsulation
"Encapsulation is defined as wrapping up of data and information under a single unit. In Object-Oriented Programming, Encapsulation is defined as
binding together the data and the functions that manipulate them."
Encapsulation also leads to data abstraction and data hiding (as using encapsulation also hides the data). This concept is of ten used to hide the
internal state representation of an object from the outside.
Encapsulation => Data Abstraction + Data Hiding
Note: Setters can be made public, as we can do validations on data or user inside the method body. So, there will be no risk to data security by
making setters as public.
Real world example of Encapsulation is medicine capsule. All medicine ingredients are encapsulated inside a single capsule.
Example
import java.lang.*;
import java.util.*;
class Pepcoder{
private String language = "Java";
private int batch = 0;
public String getLanguage()
{ return language; }
Java Page 28
Multithreading
Thread: A single thread in Java is basically a lightweight and the smallest unit of processing. There are two types of thread – user thread
and daemon thread (daemon threads are used when we want to clean the application and are used in the background, for eg, garbage
collector in Java). When an application first begins, user thread is created, and afterwards, we can create many user threads and daemon
threads. Advantage of using only single thread is that it reduces the overhead cost of the program, also reducing it's maintenance cost.
Multithreading: Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU.
Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread
runs parallel to each other. Mulitple threads don't allocate separate memory area, hence they save memory. Also, context switching
between threads takes less time.
Java Page 29
Threads can be created by using two mechanisms :
• Extending the Thread class
We can create a thread by creating a new class that extends Thread class using the following two simple steps. This approach provides
more flexibility in handling multiple threads created using available methods in Thread class.
Step 1: We need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put
your complete business logic inside this method. Following is a simple syntax of run() method −
Step 2: Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a
simple syntax of start() method.
Example:
import java.lang.*;
import java.util.*;
class myThread extends Thread {
private Thread t;
private String threadName;
Java Page 30
}
}
}
Step 1: We need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and
you will put your complete business logic inside this method.
Here, threadObj is an instance of class that implements Runnable interface and threadName is the name given to the new thread.
Step 3: Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a
simple syntax of start() method:
Example
import java.lang.*;
import java.util.*;
class myThread implements Runnable {
private Thread t;
private String threadName;
Java Page 31
}
}
}
Thread Methods
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the
static methods performs the operation on the currently running thread.
Thread Synchronization
• In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data and another thread which
Java Page 32
• In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data and another thread which
is reading data at the same time, might create inconsistency in the application.
• When there is a need to access the shared resources by two or more threads, then synchronization approach is utilized.
• Java has provided synchronized methods to implement synchronized behavior.
• In this approach, once the thread reaches inside the synchronized block, then no other thread can call that method on the same
object. All threads have to wait till that thread finishes the synchronized block and comes out of that.
• In this way, the synchronization helps in a multithreaded application. One thread has to wait till other thread finishes its execution
only then the other threads are allowed for execution.
Java Page 33