Java Upto OOps
Java Upto OOps
Concepts
Access Modifiers
Access Modifiers with Attributes
Access Modifiers with Methods and Constructors
Access Modifiers with Classes
More Method Overriding Rules
Introduction
In the previous units, we learned classes and class members like attributes, methods,
etc. In Java, it is possible to specify whether a class or any member of a class can be
accessed in another class/subclass of the same package, or another class/subclass of a
different package.
In this unit, we'll learn different types of Access Modifiers that are used to control
the accessibility.
1. Access Modifiers
Access modifiers are the keywords that set access levels when used with the classes,
methods, constructors, attributes, etc.
In Java, we have four access modifiers to set the accessibility. They are,
1. Private: The access level of a private modifier is only within the declared class.
It is not accessible outside of the class.
2. Default : The access level of a default modifier is up to the class/subclass of the
same package. It cannot be accessed from outside the package.
3. Protected : The access level of a protected modifier is up to the class/subclass
of the same package and also to a different package through the subclass. A
subclass is required to access it from a different package.
4. Public : The access level of a public modifier is everywhere in the program. It
means that it is accessible from the class/subclass of the same/different package.
Package (Recap)
Let's learn the behaviour of different modifiers with classes, methods, etc.
2.1 Private
The keyword
private
is used to specify the private access modifier. The private access modifier has the most
restricted scope among all other access modifiers.
Syntax
1
private static dataType attributeName;
JAVA
final
, and
static
are called Non-Access Modifiers. We can use access modifiers along with non-access
modifiers. When a declaration consists of both access and non-access modifiers, the
access modifiers must be placed prior to the non-access modifiers as shown above.
The
private
attributes are accessible only within the declared class.
Example 1: Accessing private attributes within the declared class
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");
System.out.println(mobile.model);
JAVA
Expand
Output
iPhone 13 Pro
In the above code, we are able to an create object and access the attribute as we have
created it inside the
Mobile
class.
Example 2: Accessing private attributes inside another class
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
}
class Base {
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");
JAVA
Expand
Output
In the above code, attribute is declared as private and tried to access it inside the
Base
class. As we have learned they are only accessed within the declared class. Hence, we
are unable to access them from any other class and the error is thrown.
The default attributes are accessible only to the classes or subclasses of the same
package. We cannot access them in other packages.
Let's understand it with an example by defining two classes in the same file.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Mobile {
String model;
String camera;
Mobile(String modelSpecification, String cameraSpecification) {
model = modelSpecification;
camera = cameraSpecification;
}
}
class Base {
JAVA
Expand
Output
iPhone 13 Pro
12 MP
In the above code, no access modifiers are mentioned for attributes. Hence, they are
considered to be the default and we are able to access the attributes of the
Mobile
class inside the
Base
class.
2.3 Protected
The keyword
protected
is used to specify the protected access modifier.
Syntax
1
protected dataType attributeName;
JAVA
protected
, it means that it is accessible to the class/subclass of the same package and subclass of
other packages.
For example, we have a public
classA
of
packageA
having a protected attribute
name
and a
classB
of
packageB
(another package). Now, the
name
is accessible inside the
classB
only when the
classB
extends
classA
.
We will learn public classes later in this unit
The access modifier
protected
is less restrictive when compared to the default and private.
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
protected String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
}
class Base {
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");
JAVA
Expand
Output
iPhone 13 Pro
In the above code, the protected attributes are accessible to other classes of the same
package. So, we are able to create objects and access the attributes and methods of it.
2.4 Public
The keyword
public
is used to specify the public access modifier.
Syntax
1
public dataType attributeName;
JAVA
public
, it means that those are accessible from the class/subclass of the same/different
package.
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
public String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
}
class Base {
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");
JAVA
Expand
Output
iPhone 13 Pro
In the above code, the public attributes are accessible from the class/subclass of the
same/different package. So, we are able to access them in another class (
Base
class) of the same package.
private Yes No No No No
3.1 Private
The methods declared with the
private
access modifier can be called private methods.
Similarly, the constructors declared with the
private
access modifiers can be called private constructors.
1
2
3
private returnType methodName() {
// method body
}
JAVA
1
2
3
private ClassName() {
// constructor body
}
JAVA
The private methods and constructors are accessible only within the declared class.
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
private Mobile(String modelSpecification) {
model = modelSpecification;
}
private void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
JAVA
Expand
Output
iPhone 13 Pro
calling...9876543210
In the above code, we are able to create objects and access the attributes and methods
of the
Mobile
class as we access them inside the
Mobile
class.
Example 2: Accessing private methods inside another class
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
private Mobile(String modelSpecification) {
model = modelSpecification;
}
private void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}
JAVA
Expand
Output
In the above code, the constructor and method are declared as private and tried to
access it inside the
Base
class. As we have learned they are only accessed within the declared class. Hence, we
are unable to access them from any other class and the error is thrown.
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}
JAVA
Expand
Output
iPhone 13 Pro
calling...9876543210
In the above code, no access modifiers are mentioned for the attribute, method, and
constructor. Hence, they are considered to be the default and we are able to access the
attributes of the
Mobile
class inside the
Base
class.
3.3 Protected
The methods and constructors declared with
protected
access modifiers can be called protected methods and protected constructors
respectively.
1
2
3
protected returnType methodName() {
// method body
}
JAVA
1
2
3
protected ClassName() {
// constructor body
}
JAVA
Similar to the protected attributes, the protected methods and constructors are
accessible to the class/subclass of the same package and subclass of other packages.
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
protected String model;
protected Mobile(String modelSpecification) {
model = modelSpecification;
}
protected void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}
JAVA
Expand
Output
iPhone 13 Pro
calling...9876543210
In the above code, the protected attributes, methods and constructors are accessible to
other classes of the same package. So, we are able to create objects and access the
attributes and methods of it.
3.4 Public
The methods and constructors declared with
public
access modifier can be called public methods and public constructors respectively.
1
2
3
public returnType methodName() {
// method body
}
JAVA
1
2
3
public ClassName() {
// constructor body
}
JAVA
Similar to the public attributes, the public methods and constructors are accessible from
can be accessed from the class/subclass of the same/different package.
Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
public String model;
public Mobile(String modelSpecification) {
model = modelSpecification;
}
public void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}
JAVA
Expand
Output
iPhone 13 Pro
calling...9876543210
In the above code, the public methods, etc are accessible from the class/subclass of the
same/different package. So, we are able to create objects and access the attributes and
methods in the
Base
class.
4.1 Public
The classes declared with
public
access modifier can be called public classes.
Syntax
1
2
3
public class ClassName {
// body of the class
}
JAVA
public
, it means that it is accessible from the class/subclass of the same/different package.
Previously we have learned what are packages. We have used different classes like
Scanner
,
Math
, etc of different packages by importing them to our Java program. This is because all
those are
public
classes. Hence, we are able to import and utilise them in our program.
A Java file can consist of only one public class.
Note: Currently we cannot define public classes in the provided code playground. We
will provide support to write public classes soon.
4.2 Default (no keyword required)
When no access modifier is specified to the classes, then they can be called default
classes.
Syntax
1
2
3
class ClassName {
// body of the class
}
JAVA
A default class is accessible only to the classes or subclasses of the same package. We
cannot access the default classes in other packages.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Mobile {
String model;
String camera;
Mobile(String modelSpecification, String cameraSpecification) {
model = modelSpecification;
camera = cameraSpecification;
}
}
class Base {
JAVA
Expand
In the above code, no access modifiers are mentioned for both classes. Hence both the
classes are considered as the default classes.
As we have learned, we can see that the
Mobile
class is accessible inside the
Base
class and able to create objects.
Similar to classes, only the access modifiers public and default we learned till now
are applicable to Interfaces also and work in the same way.
Example 1:
Code
1
2
3
4
5
6
7
8
9
10
11
class Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}
class Smartphone extends Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Smartphone");
}
JAVA
Expand
Output
smartphone
object using the superclass
Telephone
. So, the
smartphone
object can access all the methods of the
Telephone
class and overriding methods of the
Smartphone
class.
Also we tried to invoke the
makeCall()
method of the
Smartphone
class. As the private method
makeCall()
cannot be overridden, the compiler tries to invoke the
makeCall()
method of the
Telephone
class. But the private methods are only accessible in the declared class. Hence, the error
has been thrown.
Let's declare the
smartphone
object using the
Smartphone
class.
Example 2:
Code
1
2
3
4
5
6
7
8
9
10
11
class Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}
class Smartphone extends Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Smartphone");
}
JAVA
Expand
Output
makeCall()
method of the
Smartphone
class.
5. The access level cannot be more restrictive than the overridden
method's access level
We have learned that the
private
is more restrictive (i.e., narrow scope) and the
public
is less restrictive (i.e., widely scoped) access modifier.
Below is the hierarchy of the access modifiers based on the access levels, more
restrictive to less restrictive from left to right.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Telephone {
String model;
Telephone(String modelSpecification) {
model = modelSpecification;
}
protected void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}
JAVA
Expand
Output
private
modifier is more restrictive than the
protected
. So, the
makeCall()
method of the
Telephone
class cannot be overridden with the
makeCall()
method of the
Smartphone
class and the error has been thrown.
Example 2:
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Telephone {
String model;
Telephone(String modelSpecification) {
model = modelSpecification;
}
private void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}
JAVA
Expand
Output
protected
modifier is less restrictive than the
private
. So, the
makeCall()
method of the
Telephone
class has overridden by the
makeCall()
method of the
Smartphone
class.
Summary
Accessibility of Access Modifiers
private Yes No No No No
The public access modifier is having the widest scope among all the access
modifiers.
Polymorphism
Concepts
Execution of a Java Code
Polymorphism
Introduction
In the previous units, we have seen the four core principles of object-oriented
programming:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
In this unit, we'll look into the execution of Java code and learn another important
principle of OOP called Polymorphism .
1. Compilation
2. Execution
Compilation: In this stage, the file containing our Java code (with
.java
extension) is passed through the compiler, which then converts the source code (our
Java code) into a machine-independent encoding, known as Bytecode . For each class
inside the source file, a separate class file (with
.class
as file extension) is created and the corresponding code is stored in it. The class files
generated are independent of the machine or OS (Operating System).
Note: The creation of bytecode,
.class
files, etc will happen internally in the code playground provided to you.
Execution: In this stage, the main class file i.e., the class that contains the
main()
method is passed to the Java Virtual Machine (JVM) and the code will be run after a few
checks like variables are initialized before they are used, rules for accessing private data
and methods are not violated, etc.
2. Polymorphism
Polymorphism is derived from two Greek words poly and morphs. The word poly means
"many" and morphs means "forms". So polymorphism means many forms.
1. Compile-time polymorphism
2. Runtime polymorphism
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Shapes {
public void area(int radius) {
System.out.println("Area of Circle = " + 3.14 * radius * radius);
}
public void area(double base, double height) {
System.out.println("Area of Triangle = " + 0.5 * base * height);
}
public void area(int length, int breadth) {
System.out.println("Area of Rectangle = " + length * breadth);
JAVA
Expand
Output
area
which differ in their parameters. We have also invoked the same method with different
numbers or types of arguments.
Here, compile-time polymorphism occurs and the decision of which method to be
invoked for which call is done in the compilation stage.
Code
1
2
3
4
5
6
7
8
9
10
11
class Mammal {
void eat() {
System.out.println("Mammal is eating");
}
}
class Dog extends Mammal {
void eat() {
System.out.println("Dog is eating");
}
}
JAVA
Expand
Output
Dog is eating
In the above code, we have used the superclass reference variable
mammal
to refer to its subclass object. We also invoked
eat()
method using the reference variable
mammal
. The method invocations with objects are resolved (i.e., deciding which method should
be called by the statement
mammal.eat()
) during the runtime.
During the runtime, the
mammal
refers to the
Dog
object and the method invocation is resolved and the
eat()
method of the
Dog
class has been invoked as it overrides the
eat()
method of the
Mammal
class.
Summary
The execution of a Java code will be commenced in two stages:- Compilation and
Execution.
Encapsulation
Concepts
Encapsulation
Getters and Setters
Introduction
In the previous units, we have seen the four core principles of object-oriented
programming:
1. Inheritance
2. Encapsulation
3. Polymorphism
4. Abstraction
and also learned one of the fundamental principles of OOP called Inheritance.
In this unit, we'll learn another important principle of OOP called Encapsulation .
1. Encapsulation
Encapsulation in Java is a process of wrapping related code and data together into a
single unit, for example, a capsule which contains several medicines.
In Java, the idea behind encapsulation is to ensure that implementation details are not
visible to users by hiding data within a class to prevent unauthorized access and avoid
unnecessary modifications from outside the class.
Code
1
2
3
4
5
6
7
8
9
10
11
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
JAVA
Expand
Output
20
In the above code, we declared the attribute
age
, and
getAge()
,
setAge()
methods in the
Student
class. Here, we have bundled similar codes together in a single class.
To hide the implementation details, we have declared the
age
attribute as
private
and defined public methods
setAge()
and
getAge()
in the class.
This will restrict access to the attributes from outside the class. This is called Data
Hiding .
Getters: The Getters are used to access/get the value of the non-static attribute of a
class. These are also called accessors.
Generally, getters start with get, followed by the variable name in camel case notation.
Example: getBalance, getName, getLength, etc.
Setters: The Setters are used to set a new value to the non-static attribute of a class.
These are also called mutators.
Generally, setters start with set, followed by the variable name in camel case notation.
Example: setBalance, setName, setLength, etc.
Getters and setters provide us with control over the data in our program. For example,
we can write conditions inside the
setAge()
method so that no one can provide an invalid age.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int studentAge) {
if (studentAge >= 3) {
age = studentAge;
}
JAVA
Expand
Output
15
15
In the above code, we have written a condition in the setter method
setAge()
that a student's age must be greater than or equal to 3. So, when
15
is provided as an argument, the
age
attribute has been updated to
15
and when
1
is provided as an argument the
age
attribute has not been updated.
Summary
Encapsulation refers to the bundling of attributes and methods inside a single
class.
Getter method returns the value of a particular non-static attribute of the class.
Setter method sets a new value to a particular non-static attribute of the class.
Getters and setters provide us with control over the data in our program.
Abstraction
Concepts
Abstraction
Abstract Classes and Methods
Implementing Abstract Classes and Methods
Abstraction vs Encapsulation
Introduction
In the previous units, we have seen the four fundamental principles of object-oriented
programming:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
Till now we learned three fundamental principles Inheritance, Encapsulation , and
Polymorphism .
In this unit, we'll learn another fundamental principle of OOP called Abstraction .
1. Abstraction
Abstraction is the process of hiding certain details and showing only essential
information to the user.
Let's look at a real-life example of a man driving a car. As far as he knows, pressing the
accelerator increases the speed of the car or applying the brakes stops it. However, he
doesn't know how the speed actually increases when pressing the accelerator. He
doesn't know anything about the car's inner mechanisms or how the accelerator,
brakes, etc., work.
1. Abstract classes
2. Interfaces
In the unit, we'll learn abstract classes and later in the course, we'll learn interfaces.
abstract
keyword is a non-access modifier, applied to classes and methods in Java. A class which
is declared with the
abstract
keyword is known as an abstract class.
Syntax
1
2
3
abstract class ClassName {
// attributes and methods
}
JAVA
Similar to regular classes, abstract classes can have constructors, attributes, static and
final methods, etc.
However,
Abstract classes cannot be instantiated i.e., we cannot create objects using the
abstract classes.
Abstract classes can have abstract methods.
Abstract classes cannot be declared as final.
Let's try to create an object of an abstract class.
Code
1
2
3
4
5
6
7
8
9
10
11
abstract class Vehicle { // abstract class
void start() {
System.out.println("Vehicle started");
}
void stop() {
System.out.println("Vehicle stopped");
}
}
class Base {
JAVA
Expand
Output
In the above code, the error has been thrown because we cannot create objects using
the abstract classes.
2.2 Abstract Methods
A method which is declared with the
abstract
keyword is known as an abstract method .
The abstract methods don't contain any implementation i.e., abstract methods do not
have a body. The abstract methods can only be declared inside abstract classes.
Syntax
1
abstract returnType methodName();
JAVA
Code
1
2
3
4
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
JAVA
The abstract classes can have abstract methods and non-abstract methods (i.e., methods
without
abstract
keyword).
Example 1:
let's inherit the
Vehicle
from a
Car
class and implement the abstract methods inside the
Car
class.
Code
1
2
3
4
5
6
7
8
9
10
11
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
class Car extends Vehicle {
void start() { // overriding abstract method
System.out.println("Car started");
};
void stop() { // overriding abstract method
JAVA
Expand
Output
Car started
Car stopped
In the above code, we have inherited the abstract class
Vehicle
. we provided the implementation for abstract methods
start()
and
stop()
inside the class
Car
and accessed them using the
car
object.
Example 2:
We can declare a reference variable of an abstract class and assign it an object of its
subclass.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
class Motorbike extends Vehicle {
void start() {
System.out.println("Motorbike started");
}
void stop() {
JAVA
Expand
Output
Motorbike started
Motorbike stopped
Truck started
Truck stopped
In the above code, the
Vehicle
is an abstract class and the
Motorbike
and
Truck
classes extend the
Vehicle
. We declared a superclass reference variable
vehicle
.
The
start()
and
stop()
methods of
Motorbike
and
Truck
are different in their implementations. Still, we can invoke those methods using the
variable
vehicle
without knowing how they are implemented.
Here, the
start
and
stop
mechanisms may differ for different vehicles, but every vehicle consists of
start
and
stop
features regardless of the inner mechanisms.
The abstract classes focus on what should be done and not on how it should be done.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
abstract class Car extends Vehicle { // abstract class
boolean areHeadlightsOn;
Car() {
areHeadlightsOn = false;
}
JAVA
Expand
Output
Ferrari started
Ferrari stopped
Are headlights turned on: true
Ferrari handbrake applied
In the above code,
Ferrari
is a concrete class.
The
Car
class in the above code has two non-abstract methods. Hence, only partial abstraction is
achieved here.
Key Points:
Abstract Class:
o An abstract class must be declared with an
abstract
keyword.
Abstract Method :
o An abstract method must be declared with an
abstract
keyword.
4. Possible Mistakes
Let's look at the most common mistakes while working with abstract classes.
Code
1
2
3
4
5
6
7
8
9
10
11
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
class Car extends Vehicle {
void start() {
System.out.println("Car started");
};
}
JAVA
Expand
Output
file.java:6: error: Car is not abstract and does not override abstract
method stop() in Vehicle
class Car extends Vehicle {
^
Car
is not an abstract class and doesn't implement the abstract method
stop()
. Hence, the error has been thrown.
2. Declaring a method as
abstract
which cannot be overridden
We cannot declare private methods, final methods, etc as abstract as they cannot be
overridden.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
abstract class Vehicle { // abstract class
abstract final void start(); // declaring a final method as abstract
private abstract void stop(); // declaring a private method as abstract
}
class Car extends Vehicle {
void start() {
System.out.println("Car started");
}
void stop() {
JAVA
Expand
Output
start()
method is declared as
final
and the
stop()
method is declared as
private
. As the final and private methods cannot be overridden, the error has been thrown.
5. Abstraction vs Encapsulation
Following are the differences between abstraction and encapsulation:
Abstraction Encapsulation
Abstraction focus on what should be done. Encapsulation focus on How it should be done.
Summary
Abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstract Class
o An abstract class must be declared with an
abstract
keyword.
Abstract Method
o An abstract method must be declared with an
abstract
keyword.
Interfaces
Concepts
Interface
Default Methods in Interfaces
Inheritance among Interfaces
Multiple Inheritance
Abstract Classes vs Interfaces
Introduction
In the previous unit, we learned abstraction and it can be achieved by,
1. Abstract classes
2. Interfaces
1. Interface
An Interface is similar to an abstract class. It cannot be instantiated and consists of
abstract methods.
interface
keyword is used to create an interface.
Syntax
1
2
3
interface InterfaceName {
// body of the interface
}
JAVA
Similar to classes, the Pascal case notation is followed for naming the interfaces.
CricketPlayer
with an attribute
hasKit
and abstract methods as
run()
, and
field()
.
Code
1
2
3
4
5
interface CricketPlayer {
boolean hasKit = true;
void run();
void field();
}
JAVA
CricketPlayer
and declared two abstract methods.
Here, we can notice that we did not declare the abstract methods
run()
and
field()
using the
abstract
keyword.
The methods inside the interfaces are
public
and
abstract
by default. And the attributes inside the interfaces are
public
,
static
and
final
by default.
So, the above code is equivalent to,
1
2
3
4
5
interface CricketPlayer {
public static final boolean hasKit = true;
public abstract void run();
public abstract void field();
}
JAVA
implements
keyword is used to inherit interfaces from a class.
Code
1
2
3
4
5
6
7
8
9
10
11
interface CricketPlayer {
void run();
void field();
}
class Person implements CricketPlayer {
public void run() { // overriding abstract method
System.out.println("Running");
};
public void field() { // overriding abstract method
JAVA
Expand
Output
Running
Fielding
In the above code, the
Person
class implements the
CricketPlayer
interface and has overridden the
run()
and
field()
methods. We declared the overriding methods as
public
because according to the rules of overriding, the overriding method should not be more
restrictive than the overridden method.
The
public
has the widest scope among all the access modifiers. As, the methods of interfaces are
public
and
abstract
by default, specifying any other access modifier other than
public
makes the overriding methods more restrictive. Hence,
public
methods should be used to override the methods of the interfaces.
The
default
keyword is used to declare a method in the interface as default method .
Syntax
1
2
3
accessModifier default returnType methodName() {
// block of code
}
JAVA
If there are many classes that implement this interface, we would have to track down all
of these classes and make changes to them, which can be both tedious and error-prone.
To avoid this issue, Java introduced default methods, which are inherited like regular
methods and provide an implementation for the new method within the interface.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
interface OnlineShoppingSite {
void processOrder(String item);
default void sendEmailsToCustomers() { // default method
System.out.println("Sending emails to customers who made a purchase in the
last week.");
}
}
class Flipkart implements OnlineShoppingSite {
public void processOrder(String item) {
System.out.println("Processing order for " + item + " on Flipkart.");
JAVA
Expand
Output
OnlineShoppingSite
with an abstract method
processOrder(String item)
and a default method
sendEmailsToCustomers()
. The
Flipkart
class implements the
OnlineShoppingSite
interface and provides an implementation for the
processOrder(String item)
method and overrides the
sendEmailsToCustomers()
method. The Walmart class also implements the
OnlineShoppingSite
interface and provides an implementation for the
processOrder(String item)
method.
In the
main()
method, we created objects of the
Flipkart
and
Walmart
classes and called their respective methods. The
processOrder(String item)
method processes the order and the
sendEmailsToCustomers()
method sends emails to customers who made a purchase in the last week.
In the case of the
Flipkart
object, the overridden method is called, whereas in the case of the
Walmart
object, the default method is called.
extends
keyword to inherit an interface from another interface.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
interface CricketPlayer {
void run();
void field();
}
interface Wicketkeeper extends CricketPlayer { // interface extending another
interface
void wicketkeeping();
}
class Person implements Wicketkeeper {
public void field() {
JAVA
Expand
Output
Fielding
Wicketkeeping
Running
In the above code, we have extended the interface
CricketPlayer
from another interface
Wicketkeeper
and implemented all the methods in the
Person
class.
In Java,
4. Multiple Inheritance
In multiple inheritance, a single class/interface can inherit multiple interfaces.
the
ArrayList
class implements
List
,
Cloneable
, etc interfaces
o the
List
Collection
interface.
the
HashMaps
class implements
Map
,
Cloneable
, etc interfaces.
Multiple inheritance is not possible among classes i.e., a single class cannot extend
multiple classes.
Example 1: A class implementing multiple interfaces
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
interface InswingBowler {
void inswing();
}
interface OutswingBowler {
void outswing();
}
class BowlerA implements InswingBowler, OutswingBowler { // a class implementing
multiple interfaces
public void inswing() {
System.out.println("Inswing bowling");
JAVA
Expand
Output
Inswing bowling
Outswing bowling
In the above code, we have declared two interfaces
InswingBowler
and
OutswingBowler
and implemented them inside the
BowlerA
class.
The interfaces represent the IS-A relationship. Here, the
BowlerA
is a
InswingBowler
and the
BowlerA
is a
OutswingBowler
.
Example 2: An interface extending multiple interfaces
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
interface Camera {
void captureImage();
}
interface Calculator {
void calculate();
}
interface Smartphone extends Camera, Calculator { // interface extending multiple
interfaces
void videoCall();
}
JAVA
Expand
Output
Image captured
Calculate mathematical expressions
Video calling
In the above code, the
Smartphone
interface extends two superinterfaces
Camera
and
Calculator
. We declared another class
IPhone
and have provided implementation for all the methods inside it.
Similar to using a superclass reference variable, we have used an interface reference
variable
smartphone
to store the object of its subclass
IPhone
.
While using the superclass or superinterface reference variable make sure that it has all
the methods that are implemented in the subclass object that it will be storing in the
runtime.
For example, in the above code, we cannot use the reference variable of a
Camera
because it doesn't have the
calculate()
and
videoCall()
methods. The
Smartphone
interface has all the methods the
IPhone
class implemented as it extended the
Camera
and
Calculator
interfaces.
Syntax
1
2
3
class Subclass extends Superclass implements InterfaceOne, InterfaceTwo, ... {
// body of the subclass
}
JAVA
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
interface MachineGun {
void fireBullets();
}
interface MissileSystem {
void fireMissiles();
}
abstract class Boat {
abstract void move();
}
JAVA
Expand
Output
Moving
Firing bullets
Firing missiles
In the above code, we have extended the abstract class
Boat
and implemented the
MachineGun
and
MissileSystem
interfaces from a single class
Warship
. We have provided all the implementations for the methods declared in the interfaces
and an abstract class.
The abstract keyword is used to declare an abstract The interface keyword is used to declare
class. an interface.
An abstract class can have final, non-final, static and Every attribute is public, static and final by
non-static attributes. default.
An abstract class can provide the implementation of Interface can't provide the implementation
interface. of abstract class.
An abstract class can extend another Java class and An interface can extend another Java
implement multiple Java interfaces. interface only.
An abstract class can be extended using the keyword An interface can be implemented using the
"extends". keyword "implements".
An abstract class can have class members like private, Members of a Java interface are public by
protected, etc. default.
When we want to share among several closely related classes. For example:
Vehicle, Car, etc.
When the subclass that extending our abstract class has many common methods
or attributes or requires access modifiers other than
public
When we want to declare non-static and non-final attributes.
Use Interfaces:
When we expect that an unrelated class may implement our code. For example, a
smartphone implementing a calculator interface.
When we want to use the multiple inheritance.
Summary
Interfaces
o Interfaces are similar to abstract classes. It cannot be instantiated and
consists of abstract methods.
public
static
and
final
by default.
public
and
abstract
by default
o The
default
keyword is used to declare a method in the interface as default method.
Multiple Inheritance
o a single class/interface can inherit multiple interfaces.
o a single class can extend another class and implement multiple interfaces.
Multiple inheritance is not possible among classes i.e., a single class cannot
extend multiple classes.
Introduction
When executing Java code, different errors and exceptions might occur. There can
be many reasons for these errors and exceptions like coding mistakes committed by the
programmer, environmental issues like insufficient memory, network issues, etc.
To build a reliable, robust application and provide a good experience to the user we
need to handle them properly.
Code
1
2
3
4
5
class Main (
public static void main(String[] args) {
System.out.println("Hello world!");
}
)
JAVA
Output
()
instead of curly braces
{}
which results in an error.
Exceptions
Even when our code is syntactically correct, it may cause an error when an attempt is
made to execute it.
Code
1
2
3
4
5
6
7
8
class Main {
public static void main(String[] args) {
int num1 = 5;
int num2 = 0;
int result = num1 / num2;
System.out.println(result);
}
}
JAVA
Output
Throwable
class is the root class in the hierarchy and from there the hierarchy splits into two
branches Error and Exception.
1.2 Types of Exceptions
In Java, exceptions are of two types,
1. Unchecked Exceptions
2. Checked Exceptions
Unchecked Exceptions
The Unchecked exceptions mostly occur due to the errors committed by the
programmer. These exceptions are not checked at the compile-time but are checked at
the run-time. These exceptions are also known as runtime exceptions.
Code
1
2
3
4
5
6
7
class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
System.out.println(arr[6]);
}
}
JAVA
Output
ArrayIndexOutOfBoundsException
during execution.
Comparison with Python
Code
1
2
list_a = [1, 2, 3, 4]
print(list_a[6])
PYTHON
Output
Checked Exceptions
These are the exceptions that are checked by the compiler during the compile-time.
These exceptions are also called as IOExceptions.
2. Handling Exceptions
Similar to python's
try...except
block, in Java, we have
try...catch
block to handle the exceptions.
Syntax
1
2
3
4
5
6
7
8
9
try {
// body of try block
} catch (ExceptionType variableName) {
// body of catch block
}
JAVA
The
try
block includes the code that might generate an exception.
The
catch
block includes the code that is executed when there occurs an exception inside the try
block.
Code
1
2
3
4
5
6
7
8
9
10
11
12
class Main {
public static void main(String[] args) {
try {
int num1 = 5;
int num2 = 0;
int result = num1 / num2;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Denominator can't be 0");
}
}
JAVA
Expand
Output
Denominator can't be 0
Code
1
2
3
4
5
6
7
try:
num_1 = 5
num_2 = 0
result = num_1 / num_2
print(result)
except ZeroDivisionError:
print("Denominator can't be 0")
PYTHON
Output
Denominator can't be 0
2.1 Handling Multiple Exceptions
Similar to Python, in Java we can specify multiple
catch
blocks to handle different types of exceptions.
Syntax
1
2
3
4
5
6
7
8
9
10
11
try {
// body of try block
} catch (ExceptionType variableName) {
// body of catch block
} catch (ExceptionType variableName) {
// body of catch block
JAVA
Expand
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Main {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4};
System.out.println(arr[6]);
} catch (ArithmeticException e) {
System.out.println("Invalid value");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of range");
}
JAVA
Expand
Output
Code
1
2
3
4
5
6
7
8
try:
list_a = [1, 2, 3, 4]
print(list_a[6])
except ZeroDivisionError:
print("Denominator can't be 0")
except IndexError:
print("List index out of range")
PYTHON
Output
try...catch
blocks, we also have a
finally
block which is always executed whether an exception occurs inside the
try
block or not.
Syntax
1
2
3
4
5
6
7
8
9
10
11
try {
// body of try block
} catch (ExceptionType variableName) {
// body of catch block
} finally {
// body of finally block
}
JAVA
Expand
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Main {
public static void main(String[] args) {
try {
int num1 = 5;
int num2 = 0;
int result = num1 / num2;
System.out.println(result);
} catch(ArithmeticException e) {
System.out.println("Denominator can't be 0");
} finally {
System.out.println("Execution completed");
JAVA
Expand
Output
Denominator can`t be 0
Execution completed
In the above code, we are dividing a number by zero inside the
try
block, which generates
ArithmeticException
. The exception is caught by the
catch
block and then the
finally
block is executed
3. Raising Exceptions
In Java, we can throw an exception explicitly using
throw
keyword.
Code
1
2
3
4
5
6
7
8
9
class Main {
public static void main(String[] args) {
try {
throw new ArithmeticException("Denominator can't be 0");
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
JAVA
Output
Denominator can`t be 0
raise
keyword.
Code
1
2
3
4
try:
raise ZeroDivisionError("Denominator can't be 0")
except ZeroDivisionError as e:
print(str(e))
PYTHON
Output
Denominator can't be 0
`
In the above code, we are explicitly raising an
ArithmeticException
using the
throw
keyword.
The instance of the exception
e
consists of a
getMessage()
method which returns the exception message as a
string
3.1 The
throws
Keyword
In Java,
throws
keyword is used to specify the type of exception that might be thrown by a method.
Syntax
1
2
3
returnType methodName() throws ExceptionType1, ExceptionType2, ... {
// body of the method
}
JAVA
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Main {
static void divideByZero() throws ArithmeticException {
throw new ArithmeticException("Division with zero");
}
public static void main(String[] args) {
try {
divideByZero();
} catch (ArithmeticException e) {
System.out.println(e);
}
JAVA
Expand
Output
divideByZero()
method might throw an
ArithmeticException
using the
throws
keyword.
Summary
Errors detected during execution are called exceptions
The
Throwable
class is a root class from which the Error and Exception classes are derived.
The exceptions that are not checked at the compile-time but are checked at the
run-time are called Unchecked exceptions.
The exceptions that are checked at the compile-time are called as checked
exceptions.
In Java, we can use
try...catch
block for handling exceptions.
The
finally
block will execute whether an exception occurs inside the
try
block or not.
In Java, we can throw an exception explicitly using
throw
keyword
In Java,
throws
keyword is used to specify the type of exception that might be thrown by a
method.
Introduction
Java has a built-in
java.time
package which provides various classes to work with date and time.
Commonly used classes in the
java.time
package are:
LocalDate
class
LocalTime
class
LocalDateTime
class
DateTimeFormatter
class
Period
class
Duration
class
1. Working with
LocalDate
class
1.1 Representing Date
Java
LocalDate
class allows us to create a date object and represent a valid date (year, month and
day).
The
of()
method of
LocalDate
class is used to create an instance of
LocalDate
from the given year, month and day.
Code
1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2019, 4, 13);
System.out.println(dateObj);
}
}
JAVA
Output
2019-04-13
Code
1
2
3
4
from datetime import date
date_obj = date(2019, 4, 13)
print(date_obj)
PYTHON
Output
2019-04-13
of()
method leads to an error.
Code
1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2022, 2, 31);
System.out.println(dateObj);
}
}
JAVA
Output
In the above code, we have provided 31 days for the month of February. As the
February month doesn't have 31 days, the
DateTimeException
has been thrown.
LocalDate
class provides
now()
method which returns the date object with today's date.
Code
1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.now();
System.out.println(dateObj);
}
}
JAVA
Output
2022-12-20
getValue() Returns the int value of the day of the week (1, 2...7)
Returns the negative integer if the given date is less, positive integer if the
compareTo(date)
given date is greater
Example 1:
Code
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2019, 4, 13);
System.out.println(dateObj.getYear());
System.out.println(dateObj.getMonth());
System.out.println(dateObj.getDayOfWeek());
System.out.println(dateObj.getDayOfWeek().getValue());
}
}
JAVA
Expand
Output
2019
APRIL
SATURDAY
6
Example 2:
Code
1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2019, 4, 13);
System.out.println(dateObj.plusYears(5));
}
}
JAVA
Output
2024-04-13
Example 3:
Code
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj1 = LocalDate.of(2019, 4, 13);
LocalDate dateObj2 = LocalDate.of(2020, 4, 13);
if (dateObj1.compareTo(dateObj2) < 0) {
System.out.println("dateObj1 < dateObj2");
} else if (dateObj1.compareTo(dateObj2) > 0) {
System.out.println("dateObj1 > dateObj2");
} else {
JAVA
Expand
Output
dateObj1
is less than the
dateObj2
. So, the expression
dateObj1.compareTo(dateObj2) < 0
evaluates to
true
and the dateObj1 < dateObj2 is displayed on the console.
2. Working with
LocalTime
class
2.1 Representing Time
Java
LocalTime
class allows us to create a time object and represent a valid time (hours, minutes and
seconds).
Code
1
2
3
4
5
6
7
8
import java.time.LocalTime;
class Main {
public static void main(String[] args) {
LocalTime timeObj = LocalTime.of(11, 34, 56);
System.out.println(timeObj);
}
}
JAVA
Output
11:34:56
Returns the negative integer if the given time is less, positive integer if the
compareTo(time)
given time is greater
Code
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalTime;
class Main {
public static void main(String[] args) {
LocalTime timeObj = LocalTime.of(11, 34, 56);
System.out.println(timeObj);
System.out.println(timeObj.getHour());
System.out.println(timeObj.getMinute());
System.out.println(timeObj.getSecond());
}
}
JAVA
Expand
Output
11:34:56
11
34
56
Code
1
2
3
4
5
6
7
from datetime import time
time_object = time(11, 34, 56)
print(time_object)
print(time_object.hour)
print(time_object.minute)
print(time_object.second)
PYTHON
Output
11:34:56
11
34
56
3. Working with
LocalDateTime
class
3.1 Representing Date and Time
Java
LocalDateTime
class allows us to create a date-time object and represent a valid date and time
together.
Code
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDateTime;
class Main {
public static void main(String[] args) {
LocalDateTime dateTimeObj = LocalDateTime.of(2018, 11, 28, 10, 15, 26);
System.out.println(dateTimeObj.getYear());
System.out.println(dateTimeObj.getMonthValue());
System.out.println(dateTimeObj.getHour());
System.out.println(dateTimeObj.getMinute());
}
}
JAVA
Expand
Output
2018
11
10
15
Code
1
2
3
4
5
6
7
from datetime import datetime
date_time_obj = datetime(2018, 11, 28, 10, 15, 26)
print(date_time_obj.year)
print(date_time_obj.month)
print(date_time_obj.hour)
print(date_time_obj.minute)
PYTHON
Output
2018
11
10
15
4. Working with
DateTimeFormatter
class
4.1 Formatting Date and Time
The
DateTimeFormatter
class have a
ofPattern()
method that creates an instance of the
DateTimeFormatter
for the given pattern of the date, time and date-time like,
mm/dd/yyyy
hh/mm/ss
The classes
LocalDateTime
,
LocalDate
, etc have the
format()
method which accepts the
DateTimeFormatter
object of the required pattern as an argument and returns a string after formatting the
given localDate, localTime, or the localDatetime object to the specified pattern.
Example 1:
Code
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd MMM yyyy hh:mm:ss
a");
String formattedDateTime = now.format(format1);
System.out.println(formattedDateTime);
}
}
JAVA
Expand
Output
Code
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd MMMM yyyy");
String formattedDate = now.format(format1);
System.out.println(formattedDate);
}
}
JAVA
Expand
Output
13 September 2022
DateTimeFormatter
class have a
parse()
method which creates the respective object (date, time, or date-time) from the give
string.
Example 1:
Code
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
String dateStr = "28 November 2018";
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd MMMM yyyy");
LocalDate date = LocalDate.parse(dateStr, format1);
System.out.println(date);
}
}
JAVA
Expand
Output
2018-11-28
Period
class to find the difference between two dates in terms of years, months and days.
We can get the period object as the difference between two dates using
between()
method.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.time.Period;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2020, 2, 20);
LocalDate endDate = LocalDate.of(2021, 10, 21);
Period period = Period.between(startDate, endDate);
System.out.println("Years: " + period.getYears());
System.out.println("Months: " + period.getMonths());
JAVA
Expand
Output
Years: 1
Months: 8
Days: 1
Duration
class to find the difference between two times in seconds.
Code
1
2
3
4
5
6
7
8
9
10
11
12
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalTime startTime = LocalTime.of(10, 30, 30);
LocalTime endTime = LocalTime.of(10, 31, 30);
Duration duration = Duration.between(startTime, endTime);
System.out.println(duration.getSeconds());
}
JAVA
Expand
Output
60