Java Econtent
Java Econtent
Object − Objects have states and behaviors. Example: A dog has states -
color, name, breed as well as behaviors – wagging the tail, barking, eating. An
object is an instance of a class.
Objects in Java
Let us now look deep into what are objects. If we consider the real-world,
we can find many objects around us, cars, dogs, humans, etc. All these
objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the
behavior is - barking, wagging the tail, running.
If you compare the software object with a real-world object, they have
very similar characteristics.
Software objects also have a state and a behavior. A software object's
state is stored in fields and behavior is shown via methods.
So in software development, methods operate on the internal state of an
object and the object-to-object communication is done via methods.
Classes in Java
A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement
more than one interface.
5. Body: The class body surrounded by braces, { }.
Example
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
Constructors
When discussing about classes, one of the most important sub topic would be
constructors. Every class has a constructor. If we do not explicitly write a constructor
for a class, the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main
rule of constructors is that they should have the same name as the class. A class can
have more than one constructor.
Following is an example of a constructor −
Example
public class Puppy {
public Puppy() {
}
Java also supports Singleton Classes where you would be able to create only one
instance of a class.
Note − We have two different types of constructors. We are going to discuss
constructors in detail in the subsequent chapters.
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So
basically, an object is created from a class. In Java, the new keyword is used
to create new objects.
There are three steps when creating an object from a class −
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes
the new object.
Following is an example of creating an object −
Example
If we compile and run the above program, then it will produce the following result −
Output
Passed Name is :tommy
2. Difference between private, protected, public keyword or
modifiers in JAVA
Java has four access modifier namely private, protected and public. package level
access is default access level provided by Java if no access modifier is specified. These
access modifiers are used to restrict accessibility of a class, method or variable on which it
applies. We will start from private access modifier which is most restrictive access modifier
and then go towards public which is least restrictive access modifier, along the way we will
see some best practices while using access modifier in Java and some examples of
using private and protected keywords.
private keyword or modifier in java can be applied to member field, method or nested
class in Java. you can not use the private modifier on top level class. private variables,
methods, and class are only accessible on the class on which they are declared. private is
the highest form of Encapsulation Java API provides and should be used as much as
possible. It's best coding practice in Java to declare variable private by default. a
private method can only be called from the class where it has declared.
As per Rules of method overriding in Java, a private method can not be overridden as
well. the private keyword can also be applied to the constructor and if you make
constructor private you prevent it from being sub-classed. a popular example of making the
constructor private is Singleton class in Java which provides getInstance() method to get
object instead of creating a new object using the constructor in Java. here are some
differences between private and protected, public and package level access.
there is no access modifier called package instead package is a keyword which is used to
declare a package in Java, a package is a directory on which a class in Java belongs.
Package or default access level is second highest restrictive access modifier
after private and any variable, method or class declared as package-private is only
accessible on the package it belongs. the good thing about default modifier is that top level
class can also be package-private if there is no class level access modifier.
protected keyword in Java
The difference between private and protected keyword is that protected method,
variable or nested class not only accessible inside a class, inside the package but also
outside of package on a subclass. if you declare a variable protected means anyone can
use it if they extend your class. the top level class can not be make protected as well.
That's all difference between private, protected, package and public access
modifier. As you have seen the difference between private and public lies on how accessible
a particular field, method or class would have. public means you can access it anywhere
while private means you can only access it inside its own class.
3. Types of References in Java
In Java there are four types of references differentiated on the way by which they are
garbage collected.
1. Strong References
2. Weak References
3. Soft References
4. Phantom References
Prerequisite: Garbage Collection
• Strong References: This is the default type/class of Reference Object. Any object
which has an active strong reference are not eligible for garbage collection. The object
is garbage collected only when the variable which was strongly referenced points to
null.
• MyClass obj = new MyClass ();
Here ‘obj’ object is strong reference to newly created instance of MyClass,
currently obj is active object so can’t be garbage collected.
obj = null;
//'obj' object is no longer referencing to the instance.
So the 'MyClass type object is now available for garbage
collection.
class Gps
//Code..
}
public class Example
g = null;
• Weak References: Weak Reference Objects are not the default type/class of
Reference Object and they should be explicitly specified while using them.
• This type of reference is used in WeakHashMap to reference the entry objects .
• If JVM detects an object with only weak references (i.e. no strong or soft
references linked to any object object), this object will be marked for garbage
collection.
• To create such references java.lang.ref.WeakReference class is used.
• These references are used in real time applications while establishing a
DBConnection which might be cleaned up by Garbage Collector when the
application using the database gets closed.
//Java Code to illustrate Weak reference
import java.lang.ref.WeakReference;
class Gps
//code
System.out.println("GovtPolytehnicSonipat");
// Strong Reference
g.x();
g = null;
g = weakref.get();
g.x();
Output:
GovtPolitechnicSonipat
GovtPolytechnicSonipat
import java.lang.ref.SoftReference;
class Gps
//code..
System.out.println("GovtPolytechnicSonipat");
// Strong Reference
g.x();
// Creating Soft Reference to Gps-type object to which 'g'
// is also pointing.
g = null;
g = softref.get();
g.x();
Output:
GovtPolytechnicSonipat
GovtPolytechnicSonipat
Chapter-4
Inheritance (Modifiers)
You must have seen public, private and protected keywords while practising java
programs, these are called access modifiers. An access modifier restricts the
access of a class, constructor, data member and method in another class. In java
we have four access modifiers:
1. default
2. private
3. protected
4. public
To understand this example, you must have the knowledge of packages in java.
In this example we have two classes, Test class is trying to access the default
method of Addition class, since class Test belongs to a different package, this
program would throw compilation error, because the scope of default modifier is
limited to the same package in which it is declared.
Addition.java
package abcpackage;
package xyzpackage;
1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that
class from outside of the class.
class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:
In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test
class extends class Addition and the protected modifier allows the access of
protected members in subclasses (in any packages).
Addition.java
package abcpackage;
public class Addition {
33
Lets take the same example that we have seen above but this time the method
addTwoNumbers() has public modifier and class Test is able to access this
method without even extending the Addition class. This is because public
modifier has visibility everywhere.
Addition.java
package abcpackage;
package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println(obj.addTwoNumbers(100, 1));
}
}
Output:
101
Lets see the scope of these access modifiers in tabular form:
The scope of access modifiers in tabular form
------------+-------+---------+--------------+--------------+--------
| Class | Package | Subclass | Subclass |Outside|
| | |(same package)|(diff package)|Class |
————————————+———————+—————————+——————————----+—————————----—+————————
public | Yes | Yes | Yes | Yes | Yes |
————————————+———————+—————————+—————————----—+—————————----—+————————
protected | Yes | Yes | Yes | Yes | No |
————————————+———————+—————————+————————----——+————————----——+————————
default | Yes | Yes | Yes | No | No |
————————————+———————+—————————+————————----——+————————----——+————————
private | Yes | No | No | No | No |
------------+-------+---------+--------------+--------------+--------
Constructors in Java
Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection
of statements(i.e. instructions) that are executed at time of Object creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth,
and height). But when it comes to creating its object(i.e Box will now exist in computer’s memory), then
can a box be there with no value defined for its dimensions. The answer is no.
So constructors are used to assign values to the class variables at the time of object creation, either
explicitly done by the programmer or by Java itself (default constructor).
}
// We can create an object of the above class
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate calling a
// no-argument constructor
import java.io.*;
class Geek
{
int num;
String name;
Geek()
System.out.println("Constructor called");
class GFG
System.out.println(geek1.name);
System.out.println(geek1.num);
Output :
Constructor called
null
0
2. Parameterized Constructor: A constructor that has parameters is known as parameterized
constructor. If we want to initialize fields of the class with your own values, then use a
parameterized constructor.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate calling of
// parameterized constructor.
import java.io.*;
class Geek
String name;
int id;
this.name = name;
this.id = id;
class GFG
{
Output:
Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways. Compiler differentiates
constructors on the basis of numbers of parameters, types of the parameters and order of the parameters.
filter_none
edit
play_arrow
brightness_4
// Java Program to illustrate constructor overloading
// types of arguments.
import java.io.*;
class Geek
Geek(String name)
{
System.out.println("Constructor with two arguments : " +
Geek(long id)
class GFG
{
// Creating the objects of the class named 'Geek'
// type 'String'.
// type 'Long'.
Output:
Constructor with one argument - String : Shikhar
Constructor with two arguments - String and Integer : Dharmesh 26
Constructor with one argument - Long : 325614567
Constructor chaining
Constructor chaining is the process of calling one constructor from another constructor with respect to
current object.
Constructor chaining can be done in two ways:
Within same class: It can be done using this() keyword for constructors in same class
From base class: by using super() keyword to call constructor from the base class.
Constructor chaining occurs through inheritance. A sub class constructor’s task is to call super class’s
constructor first. This ensures that creation of sub class’s object starts with the initialization of the data
members of the super class. There could be any numbers of classes in inheritance chain. Every
constructor calls up the chain till class at the top is reached.
class Temp
{
// default constructor 1
Temp()
// calls constructor 2
this(5);
// parameterized constructor 2
Temp(int x)
// calls constructor 3
this(5, 15);
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y)
System.out.println(x * y);
new Temp();
Output:
75
5
The Default constructor
Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword (constructor 3 in above
example).
3. Constructor chaining can be achieved in any order.
What happens if we change the order of constructors?
Nothing, Constructor chaining can be achieved in any order
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate Constructor Chaining
class Temp
// default constructor 1
Temp()
System.out.println("default");
// parameterized constructor 2
Temp(int x)
this();
System.out.println(x);
// parameterized constructor 3
Temp(int x, int y)
this(5);
System.out.println(x * y);
{
// invokes parameterized constructor 3
Output:
default
80
NOTE: In example 1, default constructor is invoked at the end, but in example 2 default constructor is
invoked at first. Hence, order in constructor chaining is not important.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate Constructor Chaining to
class Base
String name;
// constructor 1
Base()
this("");
// constructor 2
Base(String name)
this.name = name;
+ " of base");
}
class Derived extends Base
// constructor 3
Derived()
"of derived");
// parameterized constructor 4
Derived(String name)
super(name);
"constructor of derived");
}
public static void main(String args[])
Output:
Following program illustrates how the methods of a subclass can directly access
a protected member of the superclass.
For example, let's imagine a series of classes to describe two kinds of shapes:
rectangles and triangles. These two shapes have certain common properties
height and a width (or base).
This could be represented in the world of classes with a class Shapes from
which we would derive the two other ones : Rectangle and Triangle
Program : (Shape.java)
/**
* A class Shape that holds width and height
* of any shape
*/
public class Shape
{
protected double height; // To hold height.
protected double width; //To hold width or base
/**
* The setValue method sets the data
* in the height and width field.
*/
public void setValues(double height, double width)
{
this.height = height;
this.width = width;
}
}
Program : (Rectangle.java)
/**
* This class Rectangle calculates
* the area of rectangle
*/
public class Rectangle extends Shape
{
/**
* The method returns the area
* of rectangle.
*/
public double getArea()
{
return height * width; //accessing protected members
}
}
Program : (Triangle.java)
/**
* This class Triangle calculates
* the area of triangle
*/
public class Triangle extends Shape
{
/**
* The method returns the area
* of triangle.
*/
public double getArea()
{
return height * width / 2; //accessing protected members
}
}
Program : (TestProgram.java)
/**
* This program demonstrates the Rectangle and
* Triangle class, which inherits from the Shape class.
*/
public class TestProgram
{
public static void main(String[] args)
{
//Create object of Rectangle.
Rectangle rectangle = new Rectangle();
Output :
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate the
// concept of inheritance
// base class
class Bicycle
this.gear = gear;
this.speed = speed;
speed -= decrement;
}
speed += increment;
+"\n"
}
// derived class
int startHeight)
super(gear, speed);
seatHeight = startHeight;
seatHeight = newValue;
@Override
return (super.toString()+
// driver class
{
public static void main(String args[])
System.out.println(mb.toString());
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all methods
and fields of the superclass acquire memory in this object. That is why, by using the object of the
subclass we can also access the members of a superclass.
Please note that during inheritance only object of subclass is created, not the superclass. For
more, refer Java Object Creation of Inherited Class.
Illustrative image of the program:
In practice, inheritance and polymorphism are used together in java to achieve fast performance
and readability of code.
Types of Inheritance in Java
Below are the different types of inheritance which is supported by Java.
1. Single Inheritance : In single inheritance, subclasses inherit the features of one
superclass. In image below, the class A serves as a base class for the derived class B.
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate the
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
System.out.println("Geeks");
System.out.println("for");
// Driver class
g.print_geek();
g.print_for();
g.print_geek();
Output:
Geeks
for
Geeks
import java.util.*;
import java.lang.*;
import java.io.*;
class one
System.out.println("Geeks");
System.out.println("for");
}
class three extends two
System.out.println("Geeks");
// Drived class
g.print_for();
g.print_geek();
Output:
Geeks
for
Geeks
3. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one sub class.In below image, the class A serves as a base
class for the derived class B,C and D.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
import java.util.*;
import java.lang.*;
import java.io.*;
class one
System.out.println("Geeks");
System.out.println("for");
/*............*/
// Drived class
{
public static void main(String[] args)
g.print_geek();
t.print_for();
g.print_geek();
Output:
Geeks
for
Geeks
4. Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can
have more than one superclass and inherit features from all parent classes. Please note
that Java does not support multiple inheritance with classes. In java, we can achieve
multiple inheritance only through Interfaces. In image below, Class C is derived from
interface A and B.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
import java.util.*;
import java.lang.*;
import java.io.*;
interface one
{
interface two
{
@Override
System.out.println("Geeks");
System.out.println("for");
// Drived class
c.print_geek();
c.print_for();
c.print_geek();
Output:
Geeks
for
Geeks
5. Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the above
types of inheritance. Since java doesn’t support multiple inheritance with classes, the
hybrid inheritance is also not possible with classes. In java, we can achieve hybrid
inheritance only through Interfaces.
Example
Now, the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above examples −
Example
All the reference variables d, a, v, o refer to the same Deer object in the heap.
2nd Definition
Polymorphism in Java
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism: A person at the same time can have different
characteristic. Like a man at the same time is a father, a husband, an employee. So
the same person posses different behaviour in different situations. This is called
polymorphism.
Polymorphism is considered as one of the important features of Object Oriented
Programming. Polymorphism allows us to perform a single action in different ways.
In other words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms, So it
means many forms.
n Java polymorphism is mainly divided into two types:
• Compile time Polymorphism
• Runtime Polymorphism
1. Compile time polymorphism: It is also known as static polymorphism. This
type of polymorphism is achieved by function overloading or operator
overloading.
• Method Overloading: When there are multiple functions with same name
but different parameters then these functions are said to be overloaded.
Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
1. Example: By using different types of arguments
filter_none
edit
play_arrow
brightness_4
// Java program for Method overloading
class MultiplyFun {
class Main {
public static void main(String[] args)
{
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
Output:
8
34.65
2. Example: By using different numbers of arguments
filter_none
edit
play_arrow
brightness_4
// Java program for Method overloading
class MultiplyFun {
class Main {
public static void main(String[] args)
{
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(2, 7, 3));
}
}
Output:
8
42
Example:
class OperatorOVERDDN {
class Main {
public static void main(String[] args)
{
OperatorOVERDDN obj = new OperatorOVERDDN();
obj.operator(2, 3);
obj.operator("joe", "now");
}
}
Output:
Sum = 5
Concatinated String - joenow
class Parent {
void Print()
{
System.out.println("parent class");
}
}
void Print()
{
System.out.println("subclass1");
}
}
void Print()
{
System.out.println("subclass2");
}
}
class TestPolymorphism3 {
public static void main(String[] args)
{
Parent a;
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Output:
subclass1
subclass2
Method Overloading
Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different. It is similar
to constructor overloading in Java, that allows a class to have more than one
constructor having different argument lists.
let’s get back to the point, when I say argument list it means the parameters
that a method has: For example the argument list of a method add(int a, int b)
having two parameters is different from the argument list of the method add(int
a, int b, int c) having three parameters.
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Invalid case of method overloading:
When I say argument list, I am not talking about return type of the method, for
example if two methods have same name, same parameters and have
different return type, then this is not a valid method overloading example. This
will throw compilation error.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example
of static binding where binding of method call to its definition happens at
Compile time.
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
In the above example – method disp() is overloaded based on the number of
parameters – We have two methods with the name disp but the parameters
they have are different. Both are having different number of parameters.
class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:
a
5
Example3: Overloading – Sequence of data type of
arguments
Here method disp() is overloaded based on sequence of data type of
parameters – Both the methods have different sequence of data type in
argument list. First method is having argument list as (char, int) and second is
having (int, char). Since the sequence is different, the method can be
overloaded without any issues.
class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Output:
class Demo{
void disp(int a, double b){
System.out.println("Method A");
}
void disp(int a, double b, double c){
System.out.println("Method B");
}
public static void main(String args[]){
Demo obj = new Demo();
/* I am passing float value as a second argument but
* it got promoted to the type double, because there
* wasn't any method having arg list as (int, float)
*/
obj.disp(100, 20.67f);
}
}
Output:
Method A
As you can see that I have passed the float value while calling the disp()
method but it got promoted to the double type as there wasn’t any method
with argument list as (int, float)
But this type promotion doesn’t always happen, lets see another example:
class Demo{
void disp(int a, double b){
System.out.println("Method A");
}
void disp(int a, double b, double c){
System.out.println("Method B");
}
void disp(int a, float b){
System.out.println("Method C");
}
public static void main(String args[]){
Demo obj = new Demo();
/* This time promotion won't happen as there is
* a method with arg list as (int, float)
*/
obj.disp(100, 20.67f);
}
}
Output:
Method C
As you see that this time type promotion didn’t happen because there was a
method with matching argument type.
Type Promotion table:
The data type on the left side can be promoted to the any of the data type
present in the right side of it.
Case 2:
Case 3:
Case 4:
Case 5:
// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
boxNo = num;
}
Note : The constructor calling should be first statement in the constructor body. For
example, following fragment is invalid and throws compile time error.
Box(int num)
{
boxNo = num;
Exception Handling
What Is an Exception?
The term exception is shorthand for the phrase "exceptional event."
What is an Exception?
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base
class of hierarchy. One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception. Another branch, Error are used by the Java run-time
system(JVM) to indicate errors having to do with the run-time environment
itself(JRE). StackOverflowError is an example of such an error.
How JVM handle an Exception?
See the below diagram to understand the flow of the call stack.
Example :
}
}
Output :
Exception in thread "main" java.lang.NullPointerException
at ThrowsExecp.main(File.java:8)
Try, catch, throw and throws in Java
What is an Exception?
An exception is an “unwanted or unexpected event”, which occurs during the
execution of the program i.e, at run-time, that disrupts the normal flow of the
program’s instructions. When an exception occurs, execution of the program gets
terminated.
1.try: The try block contains set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2.catch : Catch block is used to handle the uncertain condition of try block. A try
block is always followed by a catch block, which handles the exception that occurs in
associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
3.throw: Throw keyword is used to transfer control from try block to catch block.
4.throws: Throws keyword is used for exception handling without try & catch block.
It specifies the exceptions that a method can throw to the caller and does not handle
itself.
5.finally: It is executed after catch block. We basically use it to put some common
code when there are multiple catch blocks.
Example of an Exception generated by system is given below :
Exception in thread "main"
java.lang.ArithmeticException: divide
by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo: The class name
main:The method name
ExceptionDemo.java:The file name
java:5:line number
class Division {
try {
result = a / (b - c);
System.out.println("result" + result);
catch (ArithmeticException e) {
finally {
Output:
Exception caught:Division by zero
I am in final block
An example of throws keyword:
// to be handled
// by caller or caller
try {
fun();
catch (IllegalAccessException e) {
System.out.println("caught in main.");
Output:
Inside fun().
caught in main.
Difference between throw and throws
throw throws
throw keyword is declared inside a method throws keyword is used with method signature
body. (method declaration).
We cannot throw multiple exceptions using We can declare multiple exceptions (separated
throw keyword. by commas) using throws keyword.
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally
block of code is always executed whether an exception has occurred or not. Using a
finally block, it lets you run any cleanup type statements that you want to execute, no
matter what happens in the protected code. A finally block appears at the end of
catch block.
Example demonstrating finally Clause
Class ExceptionTest
System.out.println("out of try");
try
finally
Out of try
Exception in thread main java. Lang. exception array Index out of bound exception.
MyException(int a)
ex = a;
class Test
if(a<0)
else
System.out.println(a+b);
try
sum(-10, 10);
catch(MyException me)
After a method throws an exception, the runtime system leaps into action to find
someone to handle the exception. The set of possible "someones" to handle the
exception is the set of methods in the call stack of the method where the error
occurred. The runtime system searches backwards through the call stack,
beginning with the method in which the error occurred, until it finds a method that
contains an appropriate exception handler. An exception handler is considered
appropriate if the type of the exception thrown is the same as the type of exception
handled by the handler. Thus the exception bubbles up through the call stack until
an appropriate handler is found and one of the calling methods handles the
exception. The exception handler chosen is said to catch the exception.
If the runtime system exhaustively searches all of the methods on the call stack
without finding an appropriate exception handler, the runtime system (and
consequently the Java program) terminates.
To answer these questions within your read_file function, you'd have to add
a lot of code to do error detection, reporting and handling. Your function would
end up looking something like this:
errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
With error detection built in, your original 7 lines (in bold) have been inflated to
29 lines of code--a bloat factor of almost 400 percent. Worse, there's so much
error detection, reporting, and returning that the original 7 lines of code are lost
in the clutter. And worse yet, the logical flow of the code has also been lost in the
clutter, making it difficult to tell if the code is doing the right thing: Is the
file really being closed if the function fails to allocate enough memory? It's even
more difficult to ensure that the code continues to do the right thing after you
modify the function three months after writing it. Many programmers "solve" this
problem by simply ignoring it--errors are "reported" when their programs crash.
Note that exceptions don't spare you the effort of doing the work of detecting,
reporting, and handling errors. What exceptions do provide for you is the means
to separate all the grungy details of what to do when something out-of-the-
ordinary happens from the main logic of your program.
In addition, the bloat factor for error management code in this program is about
250 percent--compared to 400 percent in the previous example.
However, as you can see from the pseudo-code, ducking an exception does
require some effort on the part of the "middleman" methods. Any checked
exceptions that can be thrown within a method are part of that method's public
programming interface and must be specified in the throws clause of the method.
Thus a method informs its callers about the exceptions that it can throw, so that
the callers can intelligently and consciously decide what to do about those
exceptions.
Note again the difference in the bloat factor and code obfuscation factor of these
two error management techniques. The code that uses exceptions is more compact
and easier to understand.
Because all exceptions that are thrown within a Java program are first-class
objects, grouping or categorization of exceptions is a natural outcome of the class
hierarchy. Java exceptions must be instances of Throwable or
any Throwable descendant. As for other Java classes, you can create subclasses of
the Throwable class and subclasses of your subclasses. Each "leaf" class (a class
with no subclasses) represents a specific type of exception and each "node" class (a
class with one or more subclasses) represents a group of related exceptions.
What is Interface?
The interface is a blueprint that can be used to implement a class. The interface does not contain
any concrete methods (methods that have code). All the methods of an interface are abstract
methods.
An interface cannot be instantiated. However, classes that implement interfaces can be instantiated.
Interfaces never contain instance variables but, they can contain public static final variables (i.e.,
constant class variables)
A class which has the abstract keyword in its declaration is called abstract class. Abstract classes
should have at least one abstract method. , i.e., methods without a body. It can have multiple
concrete methods.
Abstract classes allow you to create blueprints for concrete classes. But the inheriting class should
implement the abstract method.
Allows you to separate the definition of a method from the inheritance hierarchy
Interface Syntax
interface name{
//methods
interface Pet {
p.test();
// code
int b = 20;
obj.b = 200;
obj.calculateArea();
}
Multiple Inheritance Using Interface
Definition
Inheritance is when an object or class is based on another object or class, using the same
implementation specifying implementation to maintain the same behavior. It is a
mechanism for code reuse and to allow independent extensions of the original software
via public classes and interfaces. The relationships of objects or classes through
inheritance give rise to a hierarchy. Multiple Inheritance allows a class to have more than
one super class and to inherit features from all parent class. it is achieved using interface.
Syntax
public interface A{
//Do Something
}
public interface B extends A{
//Do Something
}
public interface C extends A{
//Do Something
}
interface vehicleone{
int speed=90;
public void distance();
}
interface vehicletwo{
int distance=100;
public void speed();
}
class MultipleInheritanceUsingInterface{
public static void main(String args[]){
System.out.println("Vehicle");
obj.distance();
obj.speed();
}
}
Multiple Inheritance is a feature of object oriented concept, where a class can
inherit properties of more than one parent class. The problem occurs when
there exist methods with same signature in both the super classes and
subclass. On calling the method, the compiler cannot determine which class
method to be called and even on calling which class method gets the priority.
Why Java doesn’t support Multiple Inheritance?
Compiler Error
From the code, we see that, on calling the method fun() using Test object will cause
complications such as whether to call Parent1’s fun() or Parent2’s fun() method.
1. The Diamond Problem:
GrandParent
/ \
/ \
Parent1 Parent2
\ /
\ /
Test
filter_none
edit
play_arrow
brightness_4
// A Grand parent class in diamond
class GrandParent
{
void fun()
{
System.out.println("Grandparent");
}
}
How are above problems handled for Default Methods and Interfaces ?
interface PI2
{
// Default method
default void show()
{
System.out.println("Default PI2");
}
}
filter_none
edit
play_arrow
brightness_4
// A simple Java program to demonstrate how diamond
// problem is handled in case of default methods
interface GPI
{
// default method
default void show()
{
System.out.println("Default GPI");
}
}
Perhaps in your daily Java coding, you see (and use) upcasting and down casting occasionally.
You may hear the terms ‘casting’, ‘upcasting’, ‘down casting’ from someone or somewhere, and
you may be confused about them.
As you read on, you will realize that upcasting and down casting are really simple.
Before we go into the details, suppose that we have the following class hierarchy:
Mammal > Animal > Dog, Cat
System.out.println("Eating...");
System.out.println("Moving...");
System.out.println("Sleeping...");
System.out.println("Dog is eating...");
System.out.println("Meow Meow!");
anim.eat();
Here, we cast the Dog type to the Animal type. Because Animal is the supertype of Dog, this
casting is called upcasting.
Note that the actual object type does not change because of casting. The Dog object is still
a Dog object. Only the reference type gets changed. Hence the above code produces the
following output:
Dog is eating…
Upcasting is always safe, as we treat a type to a more general one. In the above example,
an Animal has all behaviors of a Dog.
This is also another example of upcasting:
Mammal mam = new Cat();
anim.move();
anim.eat();
}
}
Here, the teach() method can accept any object which is subtype of Animal. So objects of
type Dog and Cat will be upcasted to Animal when they are passed into this method:
Dog dog = new Dog();
trainer.teach(dog);
trainer.teach(cat);
Here, we cast the Animal type to the Cat type. As Cat is subclass of Animal, this casting is
called downcasting.
Unlike upcasting, downcasting can fail if the actual object type is not the target object type. For
example:
Animal anim = new Cat();
This will throw a ClassCastException because the actual object type is Cat. And a Cat is not
a Dog so we cannot cast it to a Dog.
The Java language provides the instanceof keyword to check type of an object before casting.
For example:
if (anim instanceof Cat) {
cat.meow();
dog.bark();
So if you are not sure about the original object type, use the instanceof operator to check the
type before casting. This eliminates the risk of a ClassCastException thrown.
// do animal-things
anim.move();
anim.eat();
dog.bark();
Here, in the teach() method, we check if there is an instance of a Dog object passed in,
downcast it to the Dog type and invoke its specific method, bark().
Okay, so far you have got the nuts and bolts of upcasting and downcasting in Java. Remember:
• Casting does not change the actual object type. Only the reference type gets changed.
• Upcasting is always safe and never fails.
• Downcasting can risk throwing a ClassCastException, so the instanceof operator is
used to check type before casting.
2nd Notes
Polymorphism in Java
Meaning of Polymorphism :
• The word polymorphism means many-form.
• In OOPs, polymorphism deals with behavior(method or function) part of the object.
• If an object is able to perform single functionality in multiple ways, this is
called polymorphic behavior of that object.
• Java polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
Types of Polymorphism :
On the basis of concept of BINDING, the polymorphism is categorized into two
category:
1. Compile Time Polymorphism
2. Runtime Polymorphism
Here, BINDING means the association of function calling with the function
definition.
1. Compile Time Polymorphism :
• If BINDING association is known at compile time then this is known as compile time
polymorphism.
• This is also known as static binding or early binding.
• Compile time polymorphism can be achieved in Java programming with the
implementation of the following programming concept
Method Overloading
Constructor Overloading
2. Runtime Polymorphism :
• If BINDING association is known at compile time that decides the association at
runtime then this is known as runtime polymorphism.
• This is also known as dynamic binding or late binding.
• Compile time polymorphism can be achieved in Java programming with the
implementation of the programming concept
Method Overriding
1. Compile Time Polymorphism :
Method Overloading
• Java allows to create more than one method with the same name in the same class.
This mechanism is called method overloading.
• In method overloading the methods name are same but the argument list of each
method must be different.
• To overload method there are three ways:
1. Define a new method with the same name with different types of argument.
2. Define a new method with the same name with different number of argument.
3. Define a new method with the same name with different types and different
number of argument.
NOTE: Return type of method, doesn't play any role in method overloading.
Example: Method overloading :
class Demo{
public void show( int a )
{
//definition
}
//Number of arguments are different
public void show( int a, int b )
{
//definition
}
//Types of arguments are different
public void show( String a, String b )
{
//definition
}
Example:
Constructor overloading :
class User{
private String name, role;
User(String name)
{
this.name = name;
}
User( String name, String role)
{
this.name = name;
this.role = role;
}
Method Overriding
• When a method in a sub-class has the same name and type signature as a method in
its super-class, then the method in the sub-class is said to override the method of the
super class.
• Both signature and return type must be the same as super class.
• The throws clause of an overriding method can have fewer types listed than the
method in the super class, or more specific types or both.
• Example :
• //Parent.java
• public class Parent
• {
• public void show()
• {
• System.out.println("Hello Parent");
• }
• }
• -------------------------------
• //Child.java
• public class Child extends Parent
• {
• //overriding
• public void show()
• {
• System.out.println("Hello Child");
• }
}
• A sub-class can change the access specifier of the method of the super-class , but only
if it provides more access.
• A method declared public in super class, will be public in sub class.
• A method declared protected in super class can be re-declared protected or public
but not private.
• A method declared default in super class can be re-declared default, protected or
public but not private.
• Fields cannot be overridden, they can only be hidden.
• To access the hidden fields use the super keyword.
• Note :
• When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass.
• Only non-static method can be override.
• Final method can't be override.
Example :
//Parent.java
public class Parent
{
public void show()
{
System.out.println("show from Parent");
}
void display()
{
System.out.println("display from Parent");
}
}
-------------------
//Child.java
public class Child extends Parent
{
public void show()
{
System.out.println("show from Child");
}
//more acces
public void display()
{
System.out.println("display from Child");
}
}
-----------------------
//MainClass.java
public class MainClass
{
public static void main(String []arg)
{
Parent p = new parent();
p.show();
p.display();
Child ch = new Child();
ch.show();
ch.diaplay();
}
}
OUTPUT :
Upcasting :
• An upcast is a cast from a derived type to one of its base classes. This cast is safe and
does not require an explicit cast notation.
• Upcasting is using the Super class's reference to refer to a Sub class's object. Or we
can say that, the act of converting a Sub class's reference into its Super class's
reference is called Upcasting.
• Syntax :
• Super-class ref = Child-class Object;
• e.g.
Parent p = new Child();
• Note :
• Through this reference you can access only those methods, which are inherited or
override by subclass, child's method can't be access.
Downcasting :
• The process of converting super class's refernce that pointing to sub-class Object, to
sub-class reference is called downcasting.
• downcasting is to be done explicit.
• Syntax ;
• Chil-class ref = (Child-class) Parent-ref.
• e.g.
Child ch = (Child) p;
Example :
Program to understand the concept
//Parent.java
public class Parent
{
public void show()
{
System.out.println("show from Parent");
}
void display()
{
System.out.println("display from Parent");
}
}
-------------------
//Child.java
public class Child extends Parent
{
//more override
public void display()
{
System.out.println("display from Child");
}
public void xyz()
{
System.out.println("Child's Method");
}
}
-----------------------
//MainClass.java
public class MainClass
{
public static void main(String []arg)
{
//Upcasting
Parent p = new Child();
p.show(); //call inherited method
p.diaplay();//call override method
p.xyz(); //ERROR
//Downcasting
Child ch = (Child) P;
ch.show(); //call inherited method
ch.diaplay();//call override method
ch.xyz(); //valid
}
}
Method overriding
Declaring a method in sub class which is already present in parent class is
known as method overriding. Overriding is done so that a child class can give
its own implementation to a method which is already provided by the parent
class. In this case the method in parent class is called overridden method and
the method in child class is called overriding method. In this guide, we will see
what is method overriding in Java and why we use it.
The purpose of Method Overriding is clear here. Child class wants to give its
own implementation so that when it calls this method, it prints Boy is eating
instead of Human is eating.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
Advantage of method overriding
The main advantage of method overriding is that the class can give its own
specific implementation to a inherited method without even modifying the
parent class code.
This is helpful when a class has several child classes, so if a child class needs
to use the parent class method, it can use it and the other classes that want to
have different implementation can use overriding feature to make changes
without touching the parent class code.
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp();
In the above example the call to the disp() method using second object (obj2)
is runtime polymorphism (or dynamic method dispatch).
Note: In dynamic method dispatch the object can call the overriding methods
of child class and all the non-overridden methods of base class but it cannot
call the methods which are newly declared in the child class. In the above
example the object obj2 is calling the disp(). However if you try to call
the newMethod() method (which has been newly declared in Demo class) using
obj2 then you would give compilation error with the following message:
class MyBaseClass{
protected void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
public void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:
17. private, static and final methods cannot be overridden as they are local
to the class. However static methods can be re-declared in the sub class,
in this case the sub-class method would act differently and will have
nothing to do with the same static method of parent class.
18. Overriding method (method of child class) can throw unchecked
exceptions, regardless of whether the overridden method(method of
parent class) throws any exception or not. However the overriding
method should not throw checked exceptions that are new or broader
than the ones declared by the overridden method. We will discuss this in
detail with example in the upcoming tutorial.
19. Binding of overridden methods happen at runtime which is known
as dynamic binding.
20. If a class is extending an abstract class or implementing
an interface then it has to override all the abstract methods unless the
class itself is a abstract class.
class ABC{
public void myMethod()
{
System.out.println("Overridden method");
}
}
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
System.out.println("Overriding method");
}
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod();
}
}
Output: