OOPs in Java
OOPs in Java
OOPs in Java
Definition
Advantages of OOPs:-
1
Structure of object-oriented programming
The structure of object-oriented programming like java includes the following things:
● Classes are user-defined data types that act as a blueprint for creating individual
objects, methods, and properties.
● Attributes represent the current state of an object. Objects will have data stored
in the attributes field. e.g., color, score, email, etc
● In the context of Java, class is a template used to create objects and define
objects' data types/properties and the methods.
2
● Classes are like categories, and objects are like items within each category.
● All the class objects should have the basic properties of the class.
● Main Core properties include the actual properties/attributes and methods used
by the object.
For example, a specific Dog is an object of the "Dogs" class in this real world. All Dogs in
the world share some characteristics from the same template. Being an animal, they
have a tail and are the faithful of all animals.
In Java, the "Dogs" class is the blueprint from which all individual Dogs can be generated
that includes all Dog's characteristics, such as race, fur color, tail length, eyes shape, etc.
So, for example, you cannot create a car from the cat class because a car must have
specific characteristics such as:- having an engine, windows, and lights — and none of
these objects' properties can be found in the dogs class.
3
● Class keyword followed by the Class name
● superclass with appropriate keyword extends (the name of a class' parent, if
available)
● appropriate Keywords depending on whether the class implements one or more
interfaces or extends from a superclass (if any)
● The class body should be enclosed within curly brackets {}
Syntax:-
● Java object is an instance of a Java class. Each object has a unique identity, a
behavior, and a state of it.
● The new keyword is used to allocate memory at runtime. All objects get memory
in the Heap memory area.
4
Object explanation with real-world entities
Java objects are pretty similar to what we come across in the real world like A Dog, a
lighter, a cat, or vehicles are all objects.
For example, a dog's state includes its color, size, gender, and age, while its behavior is
sleeping, barking, walking around like a security guard at 3 a.m.
Using the new keyword is the best way to create an instance of the class. When we
create an object by using the new keyword, it allocates memory (heap) for the
object and it also returns the reference of that object.
Syntax:-
5
Let's create a program to get familiar with classes and objects
Features of OOPs:-
Four major object-oriented programming features make them different from non-OOP
languages:
● Abstraction is the property by virtue of which only the essential details are
displayed to the user.
● Inheritance allows you to create class hierarchies, where a base class gives its
behavior and attributes to a derived class.
● Polymorphism ensures that it will execute the proper method based on the
calling object’s type.
● Encapsulation allows you to control access to your object’s state while making it
easier to maintain or change your implementation at a later date.
6
Real-world class modeling
Real-world Object-oriented class modeling designs and prepares the model’s code and
structure similar to the real-world entity. During the programming phase of
construction, the modeling is implemented by using a programming language that
supports the object-oriented programming model.
Let us take the example of a dog. In our day to day life, we see dogs of various breeds
having different colors, height, length, weight, eye color, etc.;-
So you can see here that different dog breeds are there depending upon the height, color,
tail, etc., so we can create a real-world class simulating all the dog species depending upon
the properties and methods of the class.
1
Let’s model these real-world entities into the program.
Dog.java
2
Main.java
3
Why do we need Real-world object-oriented Class modeling?
❖ To provide the feature of data hiding that is good for security concerns.
❖ It lets us write generic code: which will work with a range of data, so we don't
have to write basic stuff over and over again.
4
Example of OOPs in the Industry
Let’s consider that you are the designer of the cars in the company. You have the
sample car design and want to produce different cars with certain modifications in the
sample so that something new can be launched in the market.
● Here we will make Car class, and it will work as a basic/sample template for other
objects.
● you can further add properties if you want accordingly like TopSpeed, price,
efficiency, etc.
1
Here, car class would allow the programmer to store similar information unique to each
car (different models, name, year of manufacture, top speeds, etc.) and associate the
appropriate information.
2
Instances of a specific class can also be represented as follows :
3
Access Specifiers
● Public
● Protected
● Default
Overview
In Java, we can impose access restrictions on different data members and member
functions. The restrictions are specified through access modifiers.
Access modifiers are tags we can associate with each member to define which parts of
the program can access it directly.
There are three types of access modifiers. Let’s take a look at them one by one.
1. Private
2. Public
3. Protected
4. Default
Private:-
A private member cannot be accessed directly from outside the class. The aim
is to keep it hidden from the users and other classes. It is a popular practice to
keep the data members private since we do not want anyone manipulating
our data directly. We can make members private using the keyword private.
The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
1
When we try to access private members from outside the class, then there will be a
compile-time error.
Public:-
The public has the widest scope among all the modifiers. This tag indicates that the
members can be directly accessed by anything anywhere, either in the same package,
outside the package, inside another class, etc.
2
Here we can see that the getGun method is public, so we can call the public method
from anywhere so the public method getGun will be called by the main method, and the
getGun method has access to the private variable gun.
as the getGun() method and gun variable both are defined in the same class, so the
getGun method will access the gun variable, and the getGun() method will be accessed
by the main method.
This technique is used in data security, like those who design the program knows how
to access those variables. Anyone who is an outsider will not be able to get access to
private property. Just assume that you are designing the banking system, and any
outsider tries to know the total cash in the bank so he will not be able to do so because
he does not know which method he needs to call to fetch the data because the variable
cash can’t be accessed directly as it is private.
Here we will create the object of Cop class in the main class and call the getGun()
method with the help of object c.
Protected:-
The protected access modifier is unique. The level of access to the protected members
lies somewhere between public and private. In Java, the protected access modifier
behaves like default. But the primary use of the protected tag can be found when we
use inheritance, we will cover inheritance in detail in the upcoming section of the
course, as of now the protected data members can be accessed inside a Java package.
However, outside the package, they can only be referred to through an inherited class.
Cop.java
3
Thief.java
Class Thief will fall into a compile-time error because it is trying to access the method
fire(), and we can see that it is defined in a different package.
Default:-
If we don't use any modifier, then it is treated as the default access modifier. default is
accessible only within the same package. It cannot be accessed from another package. It
provides more accessibility than private. But, it is restrictive than protected and public
4
CLASS
1.1 Declaration
class ClassName {
The class command tells the compiler that we are creating our custom class. All the
members of the class will be defined within the class scope.
1
1.3 Creating a Class Object
The name of the class, car, will be used to create an instance of the class car in our main
program. We can create an object of a class by using the keyword new :
// Main method
public static void main(String args[]) {
}
}
2
Object
Object:-
● In Java object is an instance of a Java class. Each object has a unique identity, a
behavior, and a state of it.
● The new keyword is used to allocate memory at runtime. All objects get memory
in the Heap memory area.
1
Features used to characterize an object:
2
Object explanation with real-world entities
Java objects are pretty similar to what we come across in the real world like A Dog, a
lighter, a cat, or vehicles are all objects.
For example, a dog's state includes its color, size, gender, and age, while its behavior is
sleeping, barking, walking around like a security guard at 3 a.m.
Using the new keyword is the best way to create an instance of the class. When we
create an object by using the new keyword, it allocates memory (heap) for the
object and it also returns the reference of that object.
Syntax:-
3
Here you can see ClassName() is looking like a method used here, basically, it is a
constructor, after keyword new constructor is called so here we will study what is the
constructor;
Constructor:-
constructor is a special method because it does not have a return type. We do not even
need to write void as the return type. It is a good practice to declare/define it as the first
member method. and its name should be the same as the name of the class.
Implementation:-
4
Interview Questions
3. What happens if you don’t define a constructor in your class. Can we still create
the object of that class?
Yes, we can create that class’s object because the compiler automatically defines an
empty, default constructor inside the class, which remains hidden to the
programmer/user/outside world.
Oops is so popular because it helps in writing a complex piece of code easily, and it also
allows users to handle and maintain them easily. With OOPs, the code’s readability,
understandability, and maintainability increase multifold.
1
5. What are the differences between the class and the object?
Class Object
6. What are the differences between the constructor and the method?
2
Constructor
What is a Constructor?
It is a special method that is used to initialize the object when an object of a class is
created in the program. As the name suggests, the constructor is used to construct the
object of a class. It is called when an instance of the class is created.
o A constructor’s name must be exactly the same as the name of its class.
o The constructor is a special method because it does not have a return type. We
do not even need to write void as the return type.
o The purpose of a Java constructor is to initialize the newly created object before
it is used.
o Every time an object is created using the new() keyword, at least one constructor
is called.
Default constructor
1
Main .java
Here you can notice that we have created the object of the car class and the car
constructor of the car class is called.
Let us assume we have a bike class and we have not created any constructor within the
bike class then in that situation compiler will create the bike() constructor automatically
that will not be visible in the code.
2
Main.java
Here you can notice that the program is still running as a default constructor will be
created by the compiler automatically within the bike class which is not visible in the
program.
Basically, the purpose of the default constructor is to provide the default values to the
objects like null, 0, etc. according to the type.
3
Parameterized constructor:-
A constructor which has a certain number of parameters is called a parameterized
constructor.
4
Java Copy Constructor
There is no copy constructor in the Java language. But, we can copy the values from one
object to another object like copy constructor in other programming languages.
There are several ways to copy the values of one object into another object in Java. They
are:
● By constructor
● By assigning the values of one object to another
● By clone() method of Object class
By constructor
Here we are copying the values from one object to the other using the copy constructor
CopyConstructroExample. You can see in the following code
.
5
By assigning the values of one object to another
Here we are copying the values from one object to the other By assigning the values of
one object to another. You can see in the following code
6
Diff b/w Constructor and method in java
You need to understand that constructor is different than the method in various ways:-
7
Constructor Overloading
A constructor is just like a method in Java, but it does not have any return type. It can
also be overloaded, just like other methods.
Main.java
1
You can notice that here that I have created two different constructors.
● Student(int stdid , String stdname)
● Student(int stdid)
I have created two objects s1 and s2 using constructor-1 and constructor-2 respectively.
So I have overloaded the constructor. Constructor-2 will not be able to initialize the
name of the object so null is printed on the screen.
1. Constructor overloading means having more than one class constructor with different
signatures.
2. To compile each constructor must have a different no of parameters.
3. Parameter list consists of order and types of arguments.
4. We cannot have two constructors in a class with the same parameter lists.
2
Destructor
What is a Destructor?
In Java, when we create an object of the class. It occupies space in the memory (heap). If
we do not delete these objects, they will remain there in the memory and occupy some
space that is not useful from programming aspects. In order to resolve this problem, we
use the concept of destructor.
In this section, we will look over the alternate option to the destructor in Java. We will
also learn how we can use the finalize() method as a destructor.
The destructor is just the opposite of the constructor. The constructor is used to
initialize java objects, while the destructor is used to destroy the object in order to
release the resource and memory occupied by the object.
You need to remember that there is no concept of destructor in Java. Instead of the
destructor, Java provides an alternative as the garbage collector works the same as the
destructor in any other programming language. The garbage collector is a
thread/program that runs on the Java Virtual Machine. It automatically destroys/deletes
the unused objects (objects no longer used in the program) and frees up the memory
space. The programmer need not worry about memory management manually. It can
be error-prone, vulnerable, and may lead to a memory leak.
Advantages of Destructor
1
How does java destructor work?
When we create the object, it occupies the space in the heap memory area. In the
program, threads use these objects. If the thread no longer uses the objects, it becomes
eligible for deletion/garbage collection. The memory occupied by that object gets
available for new objects created in the program. when the garbage collector destroys
the object from the heap, the JRE(Java Runtime Environment) calls the finalize() method
to close the connections such as network connection and database connection.
It is difficult for the programmers to forcefully execute the garbage collector to destroy
the object from the heap. But Java provides an alternative method to do the same thing.
The Java Object class (parent class of all the classes in Java) provides
the finalize() method that works the same as the destructor in other programming
languages. The syntax of the finalize() method is given below:
Syntax:
It is not exactly a destructor, but it provides extra security. It ensures the use of external
resources in the program, like closing the file, etc., before closing the program. We can
call it explicitly by using the method itself or invoking the method predefined in the
java System.runFinalizersOnExit(true).
2
Example of Destructor
DestructorExample.java
3
Interview Questions
Constructor is just like a method in Java that is used to initialize the state of an object
and will be invoked during the time of object creation.
Q4. Can we have both Default Constructor and Parameterized Constructor in the
same class?
Yes, we have both Default Constructor and Parameterized Constructor in the same
class.
Q5. What happens if you don’t define a constructor in your class. Can we still
create the object of that class?
1
Yes, we can create the object of that class because the compiler defines an empty,
default constructor inside the class automatically which remains hidden to the
programmer/user/outside world.
Q6. Will the compiler create the Default Constructor when we already have a
Constructor defined in the class?
No, the compiler will not create the Default Constructor when we already have a
Constructor defined.
When we use the private keyword for a constructor then an object for the class can
only be created internally within the class, no outside class can create an object for
this class. Using this we can restrict the caller from creating objects.
class ExampleOfPrivateConstructor
{
/**
* Private Constructor for preventing object creation
from the outside class
**/
private ExampleOfPrivateConstructor (){ }
pc.display();
}
}
When we will try to run the above code we will be getting the below exception.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
2
The constructor ExampleOfPrivateConstructor () is not visible
at Sample.main(Sample.java:21)
Q8. What are the differences between the constructor and the method?
The new operator in Java creates objects. Constructor is the later step in object creation.
The constructor’s job is to initialize the members after the object has reserved memory
for itself.
3
Static
Static keyword
The static keyword is used for memory management in java. The static keyword is
used with methods, variables, blocks, and nested classes. Basically, the static keyword
belongs to the class than an instance of the class. The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
1
Java static variable
When you use a static keyword with a variable, then it is known as a static variable.
● The static variable will be shared among all the objects of the class (which is not
unique for each object),
● Memory is allocated to the static variable only once in the class area at the time
of class loading.
Just go through the code, read the comments, and have a look over the output to get a
better insight into the use of static variables.
2
Java static Method
If you use a static keyword with any method, it is called a static method.
● A static method belongs to the class rather than the object of a class.
● A static method can be invoked without creating an instance of a class.
● A static method can access static data members and can change the value of it.
3
You can notice in the above example that cube method of the calculate class is called
directly using the name of the class because static methods belong to the class rather
than the object itself.
Main.java
You can see that id is a non-static member and the main method is static so the
compiler throws a compilation error in this situation.
4
NOTE:-
We can not execute a program without the main() method. One of the ways was the
static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a
Java class without the main method.
5
Final
Final keyword
The final keyword in java is used to restrict the user. Java final keyword can be used
with the following.
1. Variable
2. Method
3. class
1
Java Final variable
once the variable is declared as final then its value can not be changed.
E.g. here in the example below, you can see that I have declared the variable speedlimit
and initialized it with a value of 90. Now, with the run method's help, when I am trying to
change its value, the compiler throws the error.
2
Here you can notice that the run method of the Bike class can not be redefined in its
child class as the run method is declared as final. So the compiler is throwing the error.
Here you can notice that the Bike class is declared as final, so we are not able to
override it; that’s why the compiler is throwing the error.
3
Super keyword
Super keyword
The super keyword in Java is a reference variable that is used to refer to the
immediate parent class object.
1
Refer to the immediate parent class variable
Here you can see that super.color prints the value of the color variable of the immediate
parent class.
2
Invoke the immediate parent class method
Here you can see that super.eat() calls the eat method of the parent class.
3
Invoke the immediate parent class method
4
this keyword
this keyword
There can be a lot of usage of Java this keyword. In Java, this is a reference variable
that refers to the current object.
1
this: refer to a current class instance variable
there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
Let’s take the case when we do not use this keyword then what happens actually
now you can notice that the values of roll no, name and fee do not change even we have
assigned the values in the constructor. this is because the compiler is not able to
distinguish local variables and instance variables because of the same names. this issue
gets resolved using this keyword.
2
this: to invoke the current class method
this can be used to invoke the current class method. But If you don't use this keyword,
the compiler automatically adds this keyword while invoking the method. Let's see the
example
3
4
this: to invoke the current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor. In other words, it is used for constructor chaining.
5
this keyword can be used to return the current class instance
We can return this keyword as a statement from the method. In such a case, the
return type of the method must be the class type (non-primitive). Let's see the
example:
6
Interview Questions
Static is a Non-Access Modifier. Static can be applied to variable, method, nested class,
and initialization blocks (static block).
If our main() method is not declared as static then the JVM has to create an object first
and call which causes the problem of having extra memory allocation.
In general, a static method means that “The Method belongs to the class and not to any
particular object” but a constructor is always invoked with respect to an object, so it
makes no sense for a constructor to be static.
Yes, it's possible to access the static variables of a class using this but it's discouraged
and as per best practices this should be used on nonstatic reference.
5. What are all the differences between this and the super keyword?
● This refers to the current class object whereas super refers to the superclass
object
● Using this we can access all non-static methods and variables. Using super we
can access superclass variables and methods from sub-class.
● Using this(); call we can call other constructors in the same class. Using super we
can call superclass constructor from sub-class constructor.
1
6. What is a final method?
When a method is declared as final, then it is called a final method, The subclass can
call the final method of the parent class but cannot override it.
Yes, the main() method can be declared as final and cannot be overridden.
When have declared a variable as static final then the variable becomes a CONSTANT.
Only one copy of the variable exists which cannot be changed by any instance.
2
Encapsulation
Definition:-
1
As a rule of thumb, a good convention is to declare all the data
members or instance variables of a class private. This will restrict direct
access from the code outside that class.
Advantages of Encapsulation
2
An Example of encapsulation:-
The goal is to prevent this bound data from any unwanted access by the
code outside this class.
Let’s understand this using an example of a very basic User class. Consider
that we are up for designing an application and are working on modeling
the log-in part of that application. We know that a user needs a username
and a password to log into the application.
A very basic User class will be modeled as: Having a field for the userName
Having a field for the password A method named login() to grant access
Whenever a new user comes, a new object can be created by passing the
userName and password to the constructor of this class. class User String
userName String password void login()
3
How can we implement Encapsulation in java:-
Note:-
Here you can see getter and setter methods we have used here in order to change the
private data members of the class because these variables are only accessible to class
methods and variables and any outside class member or object can not change these
private variables. so this is the concept of encapsulation.
4
output of above code:-
5
Inheritance
Definition:-
Inheritance is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of oops
After reading the above definition, the next question that comes to your mind is
What is the use case of inheritance? Well, the answer is that wherever we come
across an IS-A relationship between objects, we can use inheritance.
1
The Has-A relationship
here you can see these are not is-A examples instead these are Has-A
relationships between them.
2
Types of Inheritance:-
1. Single
2. Multi-level
3. Hierarchical
4. Multiple
5. Hybrid
3
Single Inheritance
When a class inherits another class, it is known as single inheritance.
4
Multilevel inheritance
When there is a chain of inheritance, it is known as multilevel inheritance.
Hierarchical inheritance
When two or more classes inherit a single class, it is known as hierarchical
inheritance. here in the example below, you can see two different classes
are inherited through the same single class.
5
multiple inheritance is not supported by java?
To reduce the complexity and simplify the language, multiple inheritance
is not supported in java.
6
Polymorphism
Definition:-
The word Polymorphism is a combination of two Greek words, Poly means
many and Morph means forms.
In programming, polymorphism refers to the same object exhibiting
different forms and behaviors. For example, take the Shape Class. The
exact shape you choose can be anything. It can be a rectangle, a circle, a
polygon, or a diamond. So, these are all shapes but their properties are
different. This is called Polymorphism
1
Types of polymorphism
● Compile-time polymorphism
● Runtime polymorphism
Compile-time polymorphism
It is also known as static polymorphism. This type of polymorphism is
achieved by Method Overloading or operator overloading
Note:- operator overloading is not supported by java.
Method overloading:-
when we have more than one function/method in the same class with the
same name and number of arguments. then these functions are known as
overloaded functions. Functions can be overloaded by a change in the
number of arguments or/and a change in the type of arguments.
Note:-different return type is not considered as overloading.
Here, you can see there are three functions in the same class having the
same name and the same number of arguments. So these functions are
overloaded.
Here we will look at an example of the same with the help of a program
written in java. We have overloaded multiply function using different
arguments types, and a number of arguments are different in each
function.
2
Main.java
3
Run-time polymorphism
It is also known as Dynamic Method Dispatch. It is a process in which a
function call to the overridden method is resolved at Runtime. Method
Overriding achieves this type of polymorphism. On the other hand,
method overriding occurs when a derived class has a definition for one of
the member functions of the base class. That base function is said to be
overridden.
Method overriding
In a simple language, when we have two classes, one is child class, and the
other is parent class, and when we write the same function in both the
child class and the parent class, the method is said to be overridden. This
concept is known as runtime polymorphism because the compiler will
decide at runtime to which function it will call during the program's
execution.
4
Here, you can easily understand that the run method is called at the
runtime, according to whether the vehicle is behaving like a car, or the
vehicle is behaving like the vehicle itself.
5
Abstraction
Definition:-
Real-world Examples #
The above illustration of the users and the admin of an application is a good
real-world example of abstraction
1
A user can only use and interact with the limited features of an application and is unaware
of the implementation details or the way the application was developed. Usually, the users
are only concerned with the functionality of an application.
An admin can have the access to a lot more features of the application and nothing is
hidden from him. The admin can monitor the activity of the users, knows how the
application was developed and can implement new features by deploying them in the
application.
In the above example, the abstraction is being applied to the user but not to the admin.
volumeUp()
Let’s look into another example of abstraction. Take the Volume button on a television
remote. With a click of a button, we request the T.V. to increase its volume. Let’s say the
button calls the Volume Up() function. The T.V. responds by producing a sound larger than
before. How the inner circuitry of the T.V. implements this is oblivious to us, yet we know
the exposed function needed to interact with the T.V.'s volume.
In Java, one can very easily see abstraction in action. Let’s take an example of Java Math class.
There are a lot of in-built methods in this class that can be used by the programmer to get
facilitated. Let’s use a few methods in our code to access the in-built functionality:
2
class TestAbstraction {
}
}
But the user doesn’t have to know about the implementation of these two methods
inside the Math class
By the definition of abstract data types, the users only get to know the essentials i.e. the
functionality of those data types, and the ‘how the implementation should be done to
achieve the specified functionality?’ part is hidden.
An example of abstract data type can be built in stack class in java in which the user knows
that it has pop push functions but the user doesn’t know how there are implemented
3
Rules for java abstract class:-
4
How can we implement abstraction in java?
when you will compiler this code by creating the object of the employee class you will get to
know that this will fall into error as this violates the rules of abstraction.AS you can not create
an object of the abstract class instead you can inherit it.
5
Now we will follow the abstraction rules. we will not create the object directly instead
we will inherit the abstract class first and implement the abstract methods of the parent
class in the child class then we will create the object of the child class.
6
7
Interface
Definition:-
An interface can be thought of as a contract that a class has to fulfill while
implementing an interface. According to this contract, the class that
implements an interface has to @Override all the abstract methods
declared in that very interface.
Declaration
the interface is declared with the Interface keyword
interface interfaceName {
// Code goes here
}
1
Why do we use an interface?
2
Example of interface
3
An Example of multiple inheritance using the interface
4
Interview Questions
1
Q4.What are the differences between abstract class and interface?
Q5.What is a superclass?
2
Q6.What is a subclass?
A subclass is a class that falls under a superclass. It inherits from the superclass
and is considered to have an “is-a” relationship with the superclass.
● Single inheritance
● Multiple inheritances
● Multi-level inheritance
● Hierarchical inheritance
● Hybrid inheritance