Unit 3 - Inheritance
Unit 3 - Inheritance
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
Example –
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output –
barking...
eating...
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();
Prof. Nikhil E. Karale, Asst Prof. IT, Sipna CoET 2
Unit 3 - Inheritance
d.bark();
d.eat();
}}
Output –
weeping...
barking...
eating...
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();
//c.bark();//C.T.Error
}}
Output -
meowing...
eating...
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
Prof. Nikhil E. Karale, Asst Prof. IT, Sipna CoET 4
Unit 3 - Inheritance
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Output -
22
24.9
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.
Example
In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.
class Vehicle{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
Output:
• The method is called with the help of a • The method is not called with the help of a
compiler compiler
A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body)
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.
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
}
}
Output –
running safely
• In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.
There are mainly three reasons to use interface. They are given below.
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.
In this example, the Bike interface has only one method, and its implementation is provided in
the Honda class.
interface Bike
Prof. Nikhil E. Karale, Asst Prof. IT, Sipna CoET 10
Unit 3 - Inheritance
{
void run(); //by default - public static
}
class Honda implements Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
}
}
Output:
running safely
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
• The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be initialized in the static block
only.
If you make any variable as final, you cannot change the value of final variable (It will
be constant).
There is a final variable speedlimit, we are going to change the value of this variable,
but It can't be changed because final variable once assigned a value can never be
changed.
Prof. Nikhil E. Karale, Asst Prof. IT, Sipna CoET 12
Unit 3 - Inheritance
class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}
Output:
class Bike
{
final void run(){System.out.println("running");
}
}
Output:
Compile Time Error
Output:
Compile Time Error
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
1) Private
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
• The protected access modifier is accessible within package and outside the package
but through inheritance only.
• The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
• It provides more accessibility than the default modifer.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output –
Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output –
Hello
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Example -
class Animal
{
String color="white";
void printColor()
{
System.out.println(color);
}
}
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
}
void demo()
{
super.printColor();//call printColor method in Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
d.demo();
}
}
Output –
black
white
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
Q.11 What do you mean by package? Explain the procedure for creating user defined
package.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
//save as A.java
package mypack;
public class A
{
private int a = 10;
public void show()
{
System.out.println("Value = " +a);
}
//save as B.java
import mypack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.show();
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
You need to use fully qualified name e.g. mypack.A etc to run the class.
Q. 12 Design an enumeration for week days and print their corresponding description
according to traditional rules.
Output
Today = Wednesday
Sunday is holiday