OOPs Concepts in Java
OOPs Concepts in Java
OOPs Concepts
1. What is an Object
2. What is a class
3. Constructor in Java
4. Object Oriented Programming Features
Abstraction
Encapsulation
Inheritance
Polymorphism
5. Abstract Class and Methods
6. Interfaces in Java
What is an Object
-1-
So if I had to write a class based on states and behaviors of House. I
can do it like this: States can be represented as instance variables and
behaviors as methods of the class.
class House {
String address;
String color;
double are;
void openDoor() {
//Write code here
}
void closeDoor() {
//Write code here
}
...
...
}
Example 2:
Let’s take another example.
Object: Car
State: Color, Brand, Weight, Model
Behavior: Break, Accelerate, Slow Down, Gear change.
Characteristics of Objects:
1. Abstraction
2. Encapsulation
3. Message passing
Message passing
A single object by itself may not be very useful. An application contains
many objects. One object interacts with another object by invoking
methods on that object. It is also referred to as Method Invocation.
See the diagram below.
-2-
What is a Class in OOPs Concepts
A class can be considered as a blueprint using which you can create as
many objects as you like. For example, here we have a
class Website that has two data members (also known as fields, instance
variables and object states). This is just a blueprint, it does not
represent any website, however using this we can create Website
objects (or instances) that represents the websites. We have created
two objects, while creating objects we provided separate properties to
the objects using constructor.
// constructor
Website(String name, int age){
this.webName = name;
this.webAge = age;
}
public static void main(String args[]){
//Creating objects
Website obj1 = new Website("beginnersbook", 5);
Website obj2 = new Website("google", 18);
-3-
Output:
beginnersbook 5
google 18
What is a Constructor
Constructor looks like a method but it is in fact not a method. It’s name
is same as class name and it does not return any value. You must have
seen this statement in almost all the programs I have shared above:
If you look at the right side of this statement, we are calling the default
constructor of class myClass to create a new object (or instance).
Example of constructor
public class ConstructorExample {
int age;
String name;
//Default constructor
ConstructorExample(){
this.name="Chaitanya";
this.age=30;
}
//Parameterized constructor
ConstructorExample(String n,int a){
this.name=n;
this.age=a;
}
public static void main(String args[]){
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 =
new ConstructorExample("Steve", 56);
System.out.println(obj1.name+" "+obj1.age);
System.out.println(obj2.name+" "+obj2.age);
}
}
Output:
Chaitanya 30
Steve 56
-4-
Object Oriented Programming features
These four features are the main OOPs Concepts that you must learn to
understand the Object Oriented Programming in Java
Abstraction
Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user. For example, when you
login to your bank account online, you enter your user_id and password
and press login, what happens when you press login, how the input
data sent to server, how it gets verified is all abstracted away from the
you.
Encapsulation
Encapsulation simply means binding object state(fields) and
behavior(methods) together. If you are creating class, you are doing
encapsulation.
-5-
Encapsulation example in Java
How to
1) Make the instance variables private so that they cannot be accessed
directly from outside the class. You can only set and get values of these
variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values
of the fields.
class EmployeeCount
{
private int numOfEmployees = 0;
public void setNoOfEmployees (int count)
{
numOfEmployees = count;
}
public double getNoOfEmployees ()
{
return numOfEmployees;
}
}
public class EncapsulationExample
{
public static void main(String args[])
{
EmployeeCount obj = new EmployeeCount ();
obj.setNoOfEmployees(5613);
System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
}
}
Output:
No Of Employees: 5613
Inheritance
The process by which one class acquires the properties and
functionalities of another class is called inheritance. Inheritance
-6-
provides the idea of reusability of code and each sub class defines only
those features that are unique to it, rest of the features can be inherited
from the parent class.
The variables and methods of the base class can be used in the child
class as well.
class A extends B
{
}
Inheritance Example
In this example, we have a parent class Teacher and a child
class MathTeacher. In the MathTeacher class we need not to write the same
code which is already present in the present class. Here we have
college name, designation and does() method that is common for all the
teachers, thus MathTeacher class does not need to write this code, the
common data members and methods can inherited from
the Teacher class.
class Teacher {
String designation = "Teacher";
String college = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}
public class MathTeacher extends Teacher{
-7-
String mainSubject = "Maths";
public static void main(String args[]){
MathTeacher obj = new MathTeacher();
System.out.println(obj.college);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:
Beginnersbook
Teacher
Maths
Teaching
Note: Multi-level inheritance is allowed in Java but not multiple
inheritance
Types of Inheritance:
-8-
Most of the new OO languages like Small Talk, Java, C# do not
support Multiple inheritance. Multiple Inheritance is supported in C++.
Polymorphism
Polymorphism is an object oriented programming feature that allows us
to perform a single action in different ways. For example, let's say we
have a class Animal that has a method animalSound(), here we cannot give
implementation to this method as we do not know which Animal class
would extend Animal class. So, we make this method abstract like this:
Now suppose we have two Animal classes Dog and Lion that
extends Animal class. We can provide the implementation detail there.
and
As you can see that although we had the common action for all
subclasses animalSound() but there were different ways to do the same
action. This is a perfect example of polymorphism (feature that allows
us to perform a single action in different ways).
-9-
Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
Polymorphism that is resolved during compiler time is known as static
polymorphism. Method overloading can be considered as static
polymorphism example.
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
public class ExampleOverloading
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
When I say method signature I am not talking about return type of the
method, for example if two methods have same name, same
parameters and have different return type, then this is not a valid
method overloading example. This will throw compilation error.
Dynamic Polymorphism
-10-
It is also known as Dynamic Method Dispatch. Dynamic polymorphism
is a process in which a call to an overridden method is resolved at
runtime rather, that's why it is called runtime polymorphism.
Example
class Animal{
public void animalSound(){
System.out.println("Default Sound");
}
}
public class Dog extends Animal{
Woof
Since both the classes, child class and parent class have the same
method animalSound. Which of the method will be called is determined at
runtime by JVM.
-11-
}
3) Example :
Constructors
Static methods
Private methods
Methods that are declared “final”
Abstract Class
abstract class A{
abstract void myMethod();
void anotherMethod(){
//Does something
}
}
-12-
A class derived from the abstract base class must implement those
methods that are not implemented(means they are abstract) in the
abstract class.
Note 3: If a child does not implement all the abstract methods of parent
class(the abstract class), then the child class must need to be declared
abstract.
//abstract class
abstract class Animal{
//abstract method
public abstract void animalSound();
}
public class Dog extends Animal{
Woof
-13-
Interfaces in Java
An interface is a blueprint of a class, which can be declared by
using interface keyword. Interfaces can contain only constants and
abstract methods (methods with only signatures no body).Like abstract
classes, Interfaces cannot be instantiated, they can only be
implemented by classes or extended by other interfaces. Interface is a
common way to achieve full abstraction in Java.
Note:
Interface: Syntax
Example of Interface:
-14-
Note:
-15-