B.Sc-III NEP JAVA UNIT-3
B.Sc-III NEP JAVA UNIT-3
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends
keyword.
Syntax
class Super
{
.....
.....
}
class Sub extends Super
{
.....
.....
}
Sample Code
class Employee
{
float salary=40000;
}
In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
}
}
Output:
meowing...
eating...
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
Method Overloading in Java.
Method overloading in Java means having two or more methods (or functions) in a class with the
same name and different arguments (or parameters). It can be with a different number of arguments or
different data types of arguments.
For instance:
void function1(double a) { ... }
void function1(int a, int b, double c) { ... }
float function1(float a) { ...}
double function1(int a, float b) { ... }
In the above example, function1() is overloaded using a different number of parameters and different data
types of parameters.
class Method_Overloading {
double figure(double l, int b) //two parameters with double type
{
return (l*b);
}
float figure(int s) //one parameter with float return type
{
return (s*s);
}
public static void main(String[] args)
{
Method_Overloading obj = new Method_Overloading();
System.out.println("Area of Rectangle: " +obj.figure(5.55, 6));
System.out.println("Area of Square: " +obj.figure(3));
}
}
class Method_Overloading {
//Method Overloading by changing the number of arguments (or parameters)
//Method 1
double figure(double l, double b) //two arguments or parameters
{
return (l*b);
}
double figure(double s) //one argument or parameter
{
return (s*s);
}
//Method 2
public static void main(String[] args) {
Method_Overloading obj = new Method_Overloading();
System.out.println("Area of Rectangle: " +obj.figure(5.55, 6.78));
System.out.println("Area of Square: " +obj.figure(3.45));
}
}
class Method_Overloading {
//Method Overloading by changing the data type of arguments (or parameters)
double figure(double l, double b) //method 1
{
return (l*b); //returns area of rectangle
}
double figure(int b, int h) //method 2
{
return ((b*h)/2); //returns area of right triangle
}
double figure(int b, double h) //method 3
{
return (b*h); //returns area of parallelogram
}
Declaring a method in the subclass which already exists there in the parent class is known as
methodoverriding. When a class is inheriting a method from a super class of its own, then there is an
option of overriding the method provided it is not declared as final. The advantage of using overriding is the
ability to classify a behavior that's specific to the child class, and the child class can implement a parent class
method based on its necessity.
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java. In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method overriding.
There are certain rules that a programmer should follow to implement overriding. These are:
In Java, a method can only be written in the child class and not in same class.
Argument list should be the same as that of the overridden method of that class.
Instance methods can also be overridden if they are inherited by the child class.
A constructor cannot be overridden.
Final - declared methods cannot be overridden.
Any method that is static cannot be used to override.
The return type must have to be the same, or a subtype of the return type declared in the original
overridden method in the parent class.
If a method cannot be inherited, then it cannot be overridden.
A child class within the same package as the instance's parent class can override any parent class
method that is not declared private or final.
A child class in a different package can only override the non-final methods declared as public or
protected.
Example:
class college {
public void move() {
System.out.println("College is open");
}
}
class univ extends college {
public void move() {
System.out.println("University is open too");
}
}
public class stud {
public static void main(String args[]) {
college a = new college();
college b = new univ();
a.move();
b.move();
}
}
Object class in Java
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that
parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be compared,
object can be cloned, object can be notified etc.
Method Description
public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long causes the current thread to wait for the specified milliseconds,
timeout)throws InterruptedException until another thread notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int causes the current thread to wait for the specified milliseconds
nanos)throws InterruptedException and nanoseconds, until another thread notifies (invokes notify()
or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
protected void finalize()throws is invoked by the garbage collector before object is being
Throwable garbage collected.
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.
Polymorphism is the ability to take more than one form. An operation mayexhibit different behavior in
different instances. The behavior depends upon the data types of data used in the operation.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from
another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a
single action in different ways.
Dynamic Binding in Java
If a body of the method at runtime is bonded to a method call then it is called dynamic binding or late
binding. This is because the method’s functionality is decided at runtime by an object in JVM. Dynamic
binding is also referred to as a run-time polymorphism. In this type of binding, the method is not decided by
the compiler. Overriding a method is a perfect example of dynamic binding in java.
When an overridden method of a class child is called through its reference of a parent type then it is
called upcasting. The type of functionality of the method’s object will be invoked. The decision of calling a
method at runtime after the compilation of code by JVM is the reason why it is called runtime
polymorphism because method binding and the display will take place after compilation.
Rules :
1. The name of the method or function of a child or parent class should be the same.
2. The parameters of methods or functions of the child and parent class must be the same.
3. The relationship should be inherited, i.e IS-A relationship.
Limitations :
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics
force the java programmer to store a specific type of objects.
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other
objects.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The
good programming strategy says it is far better to handle the problem at compile time than runtime.
The java instanceof operator is used to test whether the object is an instance of the specified type
(class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the instance
with type. It returns either true or false. If we apply the instanceof operator with any variable that has null
value, it returns false
class Simple1
{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user. A class which is declared with the abstract keyword is known as an abstract class in Java
Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing about
the message delivery.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
OUT PUT
running safely
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds
public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
In this example, the Printable interface has only one method, and its implementation is provided in the A6
class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
In this example, the Printable interface has only one method, and its implementation is provided in the
A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Output: Hello
Java Packages
A package in Java is used to group related classes. Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two
categories:
packages are the group of classes and interfaces. The grouping is done according to functionality.
Packages are containers for the classes.There are many built-in packages suchas java, lang, awt,
javax, swing, net, io, util, sql etc.
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.
The library contains components for managing input, database programming, and much much more.
The library is divided into packages and classes. Meaning you can either import a single class (along
with its methods and attributes), or a whole package that contain all the classes that belong to the specified
package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user input,
write the following code:
Example
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a
complete line:
Example
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store
them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
package mypack;
class MyPackageClass {
System.out.println("This is my package!");
CreatingPackages
The general form for creating user-defined package is
Where,
package, public & class-are the keywords
package name &class name-are the any valid user-defined package name &class name
Java.util package
Package java.util contains the collections framework, legacy collection classes, event model, date
and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).