Professional Documents
Culture Documents
Unit II-4
Unit II-4
Prepared by:
Ms.V.SWATHILAKSHMI / AP /CSE
Mr.N.BALAJI / AP /CSE
UNIT – II
Inheritance: Basic concepts - forms of inheritance - super key word – method overriding, abstract classes,
dynamic method dispatch - the Object class. Packages: Defining, Creating and Accessing, importing
packages. Interfaces: Defining, implementing, applying, variables and extending interfaces.
2MARKS
1. What is method overriding?
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java
This is possible by defining a method in the subclass that has the same name , same arguments
and same returntype as a method in the superclass
When the method is called, the method defined in the subclass is invoked and executed
instead of the one in the superclass.
}
The functionality defined in this method will never be altered in any way
6. Define inheritance
The mechanism of deriving a new from a from an old one is called inheritance The
old class is known as the base class or super class or parent class
The new class is called the subclass or derived class or child class
The inheritance allows subclasses to inherit all the variables and methods of their parent
classes
1) Abstract class can have abstract and Interface can have only abstract methods. Since Java 8,
non-abstract methods. 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 of abstract
implementation of interface. class.
5) The abstract keyword is used to The interface keyword is used to declare interface.
declare abstract class.
The members of a class can be constant or The members of an interface are always declared
variables. as constant, i.e., their values are final.
The class definition can contain the code for each The methods in an interface are abstract in
of its methods. That is, the methods can be nature, i.e., there is no code associated with
abstract or non-abstract. them. It is later defined by the class that
implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.
It can use various access specifiers like public, It can only use the public access specifier.
private or protected.
Types of access-specifiers:
24. Can you call one constructor from another if a class has multiple
constructors
Yes. Use this() syntax
5MARKS
1. Explain in detail about inheritance in java
SYNOPSIS
INTRODUCTION
USE OF INHERITANCE
FORMS OF INHERITANCE
WHY NO MULTIPLE INHERITANCE
SUPER KEYWORD
EXAMPLE PROGRAMS
INTRODUCTION:
The mechanism of deriving a new from a from an old one is called inheritance
The old class is known as the base class or super class or parent class
The new class is called the subclass or derived class or child class
The inheritance allows subclasses to inherit all the variables and methods of their parent
classes
USE OF INHERITANCE:
Code Reusability
Method Overriding (so runtime polymorphism can be achieved).
FORMS OF INHERITANCE:
Single inheritance [only one super class]
Multiple inheritance [several super classes ]
Hierarchical inheritance [ one super classes, many subclasses]
Multilevel inheritance [derived from a derived class].
Java does not directly implement multiple inheritances but by using the concept of
secondaryinheritance path in the form of interfaces.
The diagrammatical representation of the forms of inheritance is as follows:
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
The syntax of Java Inheritance
Class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
EXAMPLE:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Programmer salary is: 40000.0
Bonus of programmer is: 10000
SINGLE INHERITANCE
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...
MULTILEVEL INHERITANCE
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.
EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE
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.
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[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Example:
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
SUPER KEYWORD:
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.
USE OF SUPER:
Super is used to refer immediate parent class instance variable
super() is used to invoke immediate parent class constructor
super is used to invoke immediate parent class method
Output:
eating...
barking...
Another example of super keyword where super() is provided by the compiler implicitly.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
class Vehicle{
void run(){
System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running
1) Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
2) Method overloading is performed within Method overriding occurs in two classes that
4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
Example:
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE
Import statement must appear at the top of the file, before any class declaration
1. Declare the package at the beginning of a file using the form package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory with same name as package name under the directory where the main
source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory
Syntax:
package [PackageName];
public class [ClassName]
{
//Body of the class
}
Example:
package firstPackage; public class FirstClass
{
//Body of the class
}
Example:
//Class in package package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(“Class A”);
}
}
//Importing class from package import p1.*;
class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA(); obA.displayA();
}
Creating Packages:
Consider the following declaration: package firstPackage.secondPackage;
This package is stored in subdirectory named firstPackage.secondPackage.
A java package can contain more than one class definitions that can be declared as public.
Only one of the classes may be declared public and that class name with .java extension is the
source file name.
Default Package:
• If a source file does not begin with the package statement, the classes contained in the source
file reside in the default package
• The java compiler automatically looks in the default package to find classes
Finding Packages:
1. By default, java runtime system uses current directory as starting point and search all the
subdirectories for the package.
2. Specify a directory path using CLASSPATH environmental variable
ACCESS SPECIFIERS:
Access specifiers specifies the type of access levels for the classes, variables, methods and
constructor
Types of access-specifiers:
Example 1:
package my_package;
class A // package scope
{
// A’s public & private members
}
public class B // public scope
{
// B’s public and private members
}
Example 2:
package my_package;
class A
{
int get() { return data; } // package scope
public A(int d) { data=d;} // public scope
private int data; // private scope
}
class B
{
void f()
{
A a=new A(d);// OK A has package scope
int d=a.get(); // OK – get() has package scope
int d1=a.data;// Error! – data is private
}
}
6. Write short notes on interfaces.
INTERFACES
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body.
It is used to achieve fully abstraction and multiple inheritances in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
USE OF INTERFACE:
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritances.
It can be used to achieve loose coupling.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface
CLASS INTERFACE
The members of a class can be constant or The members of an interface are always
varaibles. declared as constant, i.e., their values are final.
The class definition can contain the code for The methods in an interface are abstract
each of its methods. That is , the methods can be in nature, i.e., there is no code associated
abstract or non-abstract. with them. It is later defined by the class
that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.
It can use various access specifiers like public, It can only use the public access specifier.
private or protected.
INTERFACE SYNTAX:
interface interfaceName
{
Variables declaration; Method declaration;
}
interface - keyword.
interfacename - any valid java variable.
obj.print();
}
}
Output: Hello
MULTIPLE INHERITANCES IN JAVA BY INTERFACE
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){ A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
10MARKS
INTRODUCTION:
The mechanism of deriving a new from a from an old one is called inheritance
The old class is known as the base class or super class or parent class
The new class is called the subclass or derived class or child class
The inheritance allows subclasses to inherit all the variables and methods of their parent
classes
USE OF INHERITANCE:
Code Reusability
Method Overriding (so runtime polymorphism can be achieved).
FORMS OF INHERITANCE:
Single inheritance [only one super class]
Multiple inheritance [several super classes ]
Hierarchical inheritance [ one super classes, many subclasses]
Multilevel inheritance [derived from a derived class].
Java does not directly implement multiple inheritances but by using the concept of
secondaryinheritance path in the form of interfaces.
The diagrammatical representation of the forms of inheritance is as follows:
EXAMPLE:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Programmer salary is: 40000.0
Bonus of programmer is: 10000
SINGLE INHERITANCE
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...
MULTILEVEL INHERITANCE
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.
EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE
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.
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[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
combination of single and hierarchical inheritance. Let me show you this diagrammatically:
C
↑
|
---------------
↑ ↑
| |
A B
↑
|
D
Example:
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
DEFINING A SUBCLASS:
}
The keyword extends signifies that the properties of the superclassname are extended to the
subclassname.
Now , the subclass contains its own variables and methods as well those of the superclass
EXAMPLE:
OUTPUT:
Parent Method
Child Method
SUPER KEYWORD:
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.
USE OF SUPER:
Super is used to refer immediate parent class instance variable
super() is used to invoke immediate parent class constructor
super is used to invoke immediate parent class method
INTERFACES
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body.
It is used to achieve fully abstraction and multiple inheritances in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
USE OF INTERFACE:
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface
CLASS INTERFACE
The members of a class can be constant or The members of an interface are always
varaibles. declared as constant, i.e., their values are final.
The class definition can contain the code for The methods in an interface are abstract
each of its methods. That is , the methods can be in nature, i.e., there is no code associated
abstract or non-abstract. with them. It is later defined by the class
that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.
It can use various access specifiers like public, It can only use the public access specifier.
private or protected.
INTERFACE SYNTAX:
interface interfaceName
{
Variables declaration; Method declaration;
}
interface - keyword.
interfacename - any valid java variable.
Output: Hello
MULTIPLE INHERITANCES IN JAVA BY INTERFACE
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){ A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Example 2:
Interface A
{
Void Adisplay();
Void Ashow();
}
Interface B
{
Void Bdisplay();
Void Bshow();
}
Class AB implements A,B
{
Void Adisplay();
{
System.out.println(A DISPLAY”);
}
Void Ashow();
{
System.out.println(A SHOW”);
}
Void Bdisplay();
{
System.out.println(B DISPLAY”);
}
Void Bshow();
{
System.out.println(B SHOW”);
}}
Class interface AB
{
Public static void main(String args[])
{
AB obj=new AB();
Obj.Adisplay();
Obj.Adshow();
Obj.Bdisplay();
Obj.Bshow();
}}
USE OF SUPER:
Super is used to refer immediate parent class instance variable
super() is used to invoke immediate parent class constructor
super is used to invoke immediate parent class method
Welcome to java
Welcome
class Vehicle
{
Vehicle()
{
System.out.println("Vehicle is created");
}
}
class Bike extends Vehicle
{
Bike()
{
super();//will invoke parent class constructor System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike();
}
}
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE
OUTPUT:
Vehicle is created
Bike is created
1. Declare the package at the beginning of a file using the form package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory with same name as package name under the directory where the main
source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory
Syntax:
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE
package [PackageName];
public class [ClassName]
{
//Body of the class
}
Example:
package firstPackage; public class FirstClass
{
//Body of the class
}
Example:
//Class in package package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(“Class A”);
}
}
//Importing class from package import p1.*;
class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA(); obA.displayA();
}
}
Creating Packages:
Consider the following declaration: package firstPackage.secondPackage;
This package is stored in subdirectory named firstPackage.secondPackage.
A java package can contain more than one class definitions that can be declared as public.
Only one of the classes may be declared public and that class name with .java extension is the
source file name.
Default Package:
• If a source file does not begin with the package statement, the classes contained in the source
file reside in the default package
• The java compiler automatically looks in the default package to find classes
Finding Packages:
3. By default, java runtime system uses current directory as starting point and search all the
subdirectories for the package.
4. Specify a directory path using CLASSPATH environmental variable
ACCESS SPECIFIERS:
Access specifiers specifies the type of access levels for the classes, variables, methods and
constructor
Types of access-specifiers:
Example 1:
package my_package;
class A // package scope
{
// A’s public & private members
}
public class B // public scope
{
// B’s public and private members
}
Example 2:
package my_package;
class A
{
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE