Lecture 3
Lecture 3
(KCS-602)
Lecture 3
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).
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.
Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
Child Class:
The class that extends the features of another class is known as child class,
sub class or derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another
class is known as parent class, super class or Base 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 {
.....
.....
}
Example:
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}
public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics";
public static void main(String args[]){
Output: Beginnersbook
PhysicsTeacher obj = new PhysicsTeacher();
Teacher
System.out.println(obj.collegeName); Physics
System.out.println(obj.designation); Teaching
System.out.println(obj.mainSubject);
obj.does();
}
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
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(); Output: barking...
d.eat();
eating...
}}
Multilevel Inheritance Example
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...");}
} Output: weeping...
barking...
class TestInheritance2{
eating...
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
Hierarchical Inheritance Example
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[]){ Output: meowing...
eating...
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
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.
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.
Method Overriding is an example of runtime polymorphism. When a parent class
reference points to the child class object then the call to the overridden method is
determined at runtime, because during method call which method(parent class or child
class) is to be executed is determined by the type of object. This process in which call to
the overridden method is resolved at runtime is known as dynamic method dispatch
Example
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[]) { Output:Boy is eating
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Example of dynamic dispatch
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();
/* When parent class reference refers to the child class object then the overriding method
(method of child class) is called.
Output: disp() method of parent class
* This is called dynamic method dispatch and runtime polymorphism */ disp() method of Child c
ABC obj2 = new Demo();
Rules of method overriding
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level.
For example: If the superclass method is declared public then the overridding method
in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared
public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
Constructors cannot be overridden.
Super keyword
The super keyword is used for calling the parent class method/constructor.
super.myMethod() calls the myMethod() method of base class while super() calls
the constructor of base 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();
Output: Overridden method
System.out.println("Overriding method"); } Overriding method
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod(); } }
Final keyword
A final variable that is not initialized at the time of declaration is known as blank final
variable. We must initialize the blank final variable in constructor of the class
otherwise it will throw a compilation error.
Example: class Demo{
//Blank final variable
final int MAX_VALUE;
Demo(){
//It must be initialized in constructor
MAX_VALUE=100; }
void myMethod(){
System.out.println(MAX_VALUE); }
public static void main(String args[]){ Output: 100
StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
Final static variable in Java
If we won’t initialize a static variable, then by default JVM will provide a default value for
static variable. But when we declare a static variable with final modifier then we should
take care of the following conventions:
Declaring variables only as static can lead to change in their values by one or more
instances of a class in which it is declared.
Declaring them as static final will help you to create a CONSTANT. Only one copy of
variable exists which can’t be reinitialize.
Important points about final static variable:
1. Initialization of variable Mandatory : If the static variable declared as final, then we
have to perform initialization explicitly whether we are using it or not and JVM won’t
provide any default value for the final static variable.
2. Initialization before class loading : For final static variable, it is compulsory that we
should perform initialization before class loading completion. We can initialize a final static
variable at the time of declaration.
3. Initialize inside a static block : We can also initialize a final static variable inside a static
block because we should initialize a final static variable before class and we know that
static block is executed before main() method.
Initialization of variable Mandatory :
class Test {
final static int x;
public static void main(String[] args)
{ System.out.println(x);
}
}
Output: Error: variable x might not have been initialized
Initialization before class
loading
/ Java program to illustrate that final static variable can be initialized at the time of
declaration
class Test {
final static int x = 10;
public static void main(String[] args)
{
System.out.println(x);
}
}
Output: 10
Initialize inside a static block
// Java program to illustrate that final static variable can be initialized inside static block
class Test {
final static int x;
static
{
x = 10;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
Output: 10
Java final method
When a method is declared with final keyword, it is called a final method. A final method
cannot be overridden.
class Bike{
final void run(){System.out.println("running");}
}
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Output: drawing rectangle
default method
Static Method in Interface
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw(); Output: drawing rectangle
27
System.out.println(Drawable.cube(3));
}}
Difference between abstract class and
interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can
have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".
8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }