Java Object-Oriented Programming Concepts
Java Object-Oriented Programming Concepts
OBJECT
ORIENTED OOPs
Concepts
PROGRAMMING
Object Oriented Programming:-
Inheritance , Encapsulation ,
Polymorphism ,Abstraction
Uday Sharma
mrudaysharma4600@[Link]
1 OOPS in JAVA
• Methods in Java:-
• Sometimes our program grows in size, and we want to separate the logic of the main
method from the other methods.
• For instance, if we calculate the average of a number pair 5 times, we can use methods
to avoid repeating the logic. [DRY – Don’t Repeat Yourself].
• Syntax of a Method:-
A method is a function written inside a class. Since Java is an object-oriented language, we need
to write the method inside some class.
• Syntax of a method :
returnType nameOfMethod() {
//Method body
}
Output:-
• Recursion in Java:-
One does not simply understand RECURSION without understanding RECURSION.
• In programming, recursion is a technique through which a function calls itself.
• With the help of recursion, we can break down complex problems into simple problems.
• Fibonacci series:-
7
class <class_name>{
field;
method;
}
Output:-
Output:-
Constructors in Java:-
• Constructors in Java : -
• Constructors are similar to methods,, but they are used to initialize an object.
• Constructors do not have any return type(not even void).
• Every time we create an object by using the new() keyword, a constructor is called.
• If we do not create a constructor by ourself, then the default constructor(created by Java
compiler) is called.
• Rules for creating a Constructor :-
1. The class name and constructor name should be the same.
2. It must have no explicit return type.
3. It can not be abstract, static, final, and synchronized.
• Types of Constructors in Java :-
There are two types of constructors in Java :
1. Defaut / Non-Parameterized constructor : A constructor with 0 parameters is
known as default constructor. A constructor which has no argument is known as non-
parameterized constructor(or no-argument constructor). It is invoked at the time of
creating an object. If we don’t create one then it is created by default by Java.
Syntax :
<class_name>(){
//code to be executed on the execution of the constructor
}
Note:-
1. Constructors can take parameters without being overloaded
2. There can be more than two overloaded constructors.
3. Note : - When an object is created using a new keyword, then space is allocated for the
variable in a heap, and the starting address is stored in the stack memory.
4. ‘this’ keyword : ‘this’ keyword in Java that refers to the current instance of the class. In
OOPS it is used to:-
5. pass the current object as a parameter to another method
6. refer to the current class instance variable.
Java Constructor Java Method
A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you The method is not provided by the compiler in any case.
don't have any constructor in a class.
The constructor name must be same as the class name. The method name may or may not be same as the class name.
14
• Inheritance:-
• Inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such a way, you can reuse, extend or modify the attributes
and behaviors which are defined in other classes.
• In Java, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
• Inheritance is used to borrow properties & methods from an existing class.
• Inheritance helps us create classes based on existing classes, which increases the code's
15
reusability.
• Inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such a way, you can reuse, extend or modify the attributes
and behaviors which are defined in other classes.
• In Java, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
Examples :
Code:-
16
• Types of Inheritance :
1. Single inheritance : -When one class inherits another class, it is known as single level
inheritance
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
}}
2. Hierarchical inheritance:- Hierarchical inheritance is defined as the process of deriving
more than one class from a base class.
class Shape {
public void area() {
17
[Link]("Displays Area of Shape");
}}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
} }
class Circle extends Shape {
public void area(int r) {
[Link]((3.14)*r*r);
} }
3. Multilevel inheritance :- Multilevel inheritance is a process of deriving a class from another
derived class.
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
} }
class EquilateralTriangle extends Triangle {
int side;
}
4. Hybrid inheritance : -Hybrid inheritance is a combination of simple, multiple inheritance and
hierarchical inheritance.
• Constructor order in the inheritance :-
When a drived class is extended from the base class, the constructor of the base class is
executed first followed by the constructor of the derived class. For the following Inheritance
hierarchy , the constructors are executed in the order:
1. C1- Parent
2. C2 - Child
3. C3 - Grandchild
• Constructors during constructor overloading :-
• When there are multiple constructors in the parent class, the constructor without any
parameters is called from the child class.
• If we want to call the constructor with parameters from the parent class, we can use the
super keyword.
• super(a, b) calls the constructor from the parent class which takes 2 variables.
Code:-
18
Output:-
• Aggregation in Java:-
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.
Consider a situation, Employee object contains many informations such as id, name, email_Id etc.
It contains one more object named address, which contains its own informations such as city,
state, country, zipcode etc. as given below.
Why use Aggregation?
o For Code Reusability.
Simple Example of Aggregation
Output:-
20
• Polymorphism:-
Polymorphism is the ability to present the same interface for differing underlying forms (data
types). With polymorphism, each of these classes will have different underlying data. Precisely,
Poly means ‘many’ and morphism means ‘forms’.
• Types of Polymorphism:-
1. Compile Time Polymorphism (Static).
2. Runtime Polymorphism (Dynamic) .
• Compile Time Polymorphism : The polymorphism which is implemented at the
compile time is known as compile-time polymorphism. Example - Method Overloading .
• Method Overloading : Method overloading is a technique which allows you to have more
than one function with the same function name but with different functionality. Method
overloading can be possible on the following basis:
1. The type of the parameters/argument passed to the function.
2. The number of parameters passed to the function.
3. We can check the overloding of method in the beginning of the notes of OOPS in JAVA
programming .
• Runtime Polymorphism : Runtime polymorphism is also known as dynamic
polymorphism. Function overriding is an example of runtime polymorphism. Function
overriding means when the child class contains the method which is already present in the
parent class. Hence, the child class overrides the method of the parent class. In case of
function overriding, parent and child classes both contain the same function with a different
definition. The call to the function is determined at runtime is known as runtime
polymorphism.
• Method Overriding in Java:-
1. If the child class implements the same method present in the parent class again, it is know as
method overriding.
2. Method overriding helps us to classify a behavior that is specific to the child class.
3. The subclass can override the method of the parent class only when the method is not declared
as final.
Example :
In the below code, we've created two classes: class A & class B.
Class B is inheriting class A.
4. In the main() method, we've created one object for both classes. We're running the meth1()
method on class A and B objects separately, but the output is the same because the meth1() is
defined in the parent class, i.e., class A.
5. Overriding method is denoted by @override which denotes this method is override ,if we
override the method then we use override to detect the error . @overriding is not necessary but
it is recommended to use in the code .
Code:-
21
Output:-
class Animal{}
class Dog extends Animal{}
Animal a=new Dog();//upcasting
Output:-
Code :-
25
Output:-
Output:-
26
● Interfaces
● All the fields in interfaces are public, static and final by default.
● All methods are public & abstract by default.
● A class that implements an interface must implement all the methods declared in the
interface( which is abstract by nature).
● Just like a class in java is a collection of the related methods, an interface in java is a
collection of abstract methods.
● The interface is one more way to achieve abstraction in Java.
● An interface may also contain constants, default methods, and static methods.
● All the methods inside an interface must have empty bodies except default methods and
static methods.
● We use the interface keyword to declare an interface.
● There is no need to write abstract keyword before declaring methods in an interface
because an interface is implicitly abstract.
● An interface cannot contain a constructor (as it cannot be used to create objects)
● In order to implement an interface, java requires a class to use the implement keyword.
● Interfaces support the functionality of multiple inheritance.
● Java Interface also represents the IS-A relationship.
The relationship between classes and interfaces:-
• The relationship between class and interface:-
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Output-
27
Outputs:-
}
Output:-
29
@Override
public void bark() {
[Link]("Dog barks!");
}
public static void main(String[] args) {
CWH obj1 = new CWH();
[Link]();
[Link]();
}}
Another Example:-
package [Link];
30 interface MyCamera{
void takeSnap();
void recordVideo();
private void greet(){
[Link]("Good Morning");
}
default void record4KVideo(){
greet();
[Link]("Recording in 4k...");
}}
interface MyWifi{
String[] getNetworks();
void connectToNetwork(String network);
}
class MyCellPhone{
void callNumber(int phoneNumber){
[Link]("Calling "+ phoneNumber);
}
void pickCall(){
[Link]("Connecting... ");
}}
class MySmartPhone extends MyCellPhone implements MyWifi, MyCamera{
public void takeSnap(){
[Link]("Taking snap");
}
public void recordVideo(){
[Link]("Taking snap");
}
// public void record4KVideo(){
// [Link]("Taking snap and recoding in 4k");
// }
public String[] getNetworks(){
[Link]("Getting List of Networks");
String[] networkList = {"Harry", "Prashanth", "Anjali5G"};
return networkList;}
public void connectToNetwork(String network){
[Link]("Connecting to " + network);
}}
public class cwh_57_default_methods {
public static void main(String[] args) {
MySmartPhone ms = new MySmartPhone();
ms.record4KVideo();
// [Link](); --> Throws an error!
String[] ar = [Link]();
for (String item: ar) {
[Link](item);
} }}
• Inheritance in Interfaces
Interfaces can extend other interfaces as shown below :
Note: Remember that interface cannot implement another interface only classes can do that!
But the interface can be Extends by using the “extends” Keyword .
• Polymorphism in Interfaces
• GPS g = new Smartphone ( ); can only use GPS method
Smartphones = new Smartphone ( ); can only use smartphone methods
• Implementing an Interface force method implementation
Code:-
32
33 ● Java Tutorial: Abstract Classes Vs Interfaces
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Output:-
Now the main class name Package_in_extended_class in which import both the
classes using import package.*;
In this the ID is protected because protected access modifiers can be pass through the same
package but if the ID is private it cannot be accessed.
36
Output:-
Note: Sequence of the program must be package then import then class.
Subpackage in java.
Package inside the package is called the subpackage. It should be created to categorize the
package further.
• Access Modifiers in Java:-
Access modifiers determine whether other classes can use a particular field or invoke a particular
method can be public, private, protected, or default ( no modifier ). See the table given below :
Access Modifier within class within package outside package by subclass only outside package
public Y Y Y Y
protected Y Y Y N
Default Y Y N N
private Y N N N
• Encapsulation in Java:-
Encapsulation in Java is a process of wrapping code and data together into a single unit , for
example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class private.
Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
37
• Advantage of Encapsulation in Java:-
• By providing only a setter or getter method, you can make the class read-only or write-only.
In other words, you can skip the getter or setter methods.
• It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.
• It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.
• The encapsulate class is easy to test. So, it is better for unit testing.
• The standard IDE's are providing the facility to generate the getters and setters. So, it is easy
and fast to create an encapsulated class in Java.
Note:- In the encapsulation the private datatypes is can be access by the getter() and the setter()
Method:-
Awesome example of using getter( ) and the setter( ) methods:-
We using the two interface Interface_student_2 and Interface_student_1in the java and
implements in the class-public class Combining_interfaces_Student_1_2
implements Interface_student_1,Interface_student_2 in the same package .
Then the package is imported in the different class public class
package_in_interfaces_student of the different package which is in same project folder
name as the Encapsulation in java.
➢ From the package package_in_example:-
❖ Interface 1:-
❖ Now calling the class in the different class which is in different package:-
Output:-
39
➢ Go check out my LinkedIn profile for more notes and other resources content
@Uday Sharma
mrudaysharma4600@[Link]
[Link]