OOPs concepts in Java
OOPs concepts in Java
We will cover each and every feature of OOPs in detail so that you won’t face any
difficultly understanding OOPs Concepts.
1. What is an Object
2. What is a class
3. Constructor in Java
4. Object Oriented Programming Features
o Abstraction
o Encapsulation
o Inheritance
o Polymorphism
5. Abstract Class and Methods
6. Interfaces in Java
What is an Object
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.
Note: As we have seen above, the states and behaviors of an object, can be
represented by variables and methods in the class respectively.
Characteristics of Objects:
If you find it hard to understand Abstraction and Encapsulation, do not worry as I
have covered these topics in detail with examples in the next section of this
guide.
1. Abstraction
2. Encapsulation
3. Message passing
Abstraction: Abstraction is a process where you show only “relevant” data and
“hide” unnecessary details of an object from the user.
Encapsulation: Encapsulation simply means binding object state(fields) and
behaviour(methods) together. If you are creating class, you are doing
encapsulation.
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.
// 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);
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:
We can also have parameters in the constructor, such constructors are known
as parametrized constructors.
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
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. Read more about it
here: Abstraction in Java.
Encapsulation
Encapsulation simply means binding object state(fields) and behavior(methods)
together. If you are creating class, you are doing encapsulation.
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
The class EncapsulationExample that is using the Object of
class EmployeeCount will not able to get the NoOfEmployees directly. It has to
use the setter and getter methods of the same class to set and get the value.
So what is the benefit of encapsulation in java programming
Well, at some point of time, if you want to change the implementation details of
the class EmployeeCount, you can freely do so without affecting the classes that
are using it.
Inheritance
The process by which one class acquires the properties and functionalities of
another class is called inheritance. Inheritance 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.
Note: The biggest advantage of Inheritance is that the code in base class need
not be rewritten in the child 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{
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:
Single Inheritance: refers to a child and parent class relationship where a class
extends the another class.
Multiple Inheritance: refers to the concept of one class extending more than one
classes, which means a child class has two parent classes. Java doesn’t support
multiple inheritance, read more about it here.
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 a object oriented programming feature that allows us to
perform a single action in different ways. For example, lets 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:
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.
Method Overloading: This allows us to have more than one methods with same
name in a class that differs in signature.
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
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,
thats 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.
• Constructors
• Static methods
• Private methods
• Methods that are declared “final”
Abstract Class
An abstract class outlines the methods but not necessarily implements all the
methods.
abstract class A{
abstract void myMethod();
void anotherMethod(){
//Does something
}
}
Note 1: There can be some scenarios where it is difficult to implement all the
methods in the base class. In such scenarios one can define the base class as
an abstract class which signifies that this base class is a special kind of class
which is not complete on its own.
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 2: Abstract class cannot be instantiated which means you cannot create
the object of abstract class. To use this class, you need to create another class
that extends this abstract class provides the implementation of abstract
methods, then you can use the object of that child class to call non-abstract
parent class methods as well as implemented methods(those that were abstract
in parent but implemented in child 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.
Example of Abstract class and Methods
Here we have an abstract class Animal that has an abstract method
animalSound(), since the animal sound differs from one animal to another, there
is no point in giving the implementation to this method as every child class must
override this method to give its own implementation details. That’s why we made
it abstract.
Now each animal must have a sound, by making this method abstract we made it
compulsory to the child class to give implementation details to this method. This
way we ensures that every animal has a sound.
//abstract class
abstract class Animal{
//abstract method
public abstract void animalSound();
}
public class Dog extends Animal{
Woof
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
Note:
Access Specifiers
Well, you must have seen public, private keyword in the examples I have shared
above. They are called access specifiers as they decide the scope of a data
member, method or class.
Source : https://beginnersbook.com/2013/04/oops-concepts/