[Go to site: main page, start]

0% found this document useful (0 votes)
20 views15 pages

Java Module 3 Notes

The document covers various concepts of inheritance and interfaces in Java, including types of inheritance, method overriding, dynamic method dispatch, abstract classes, and the use of the final keyword. It provides definitions, examples, and comparisons of abstract classes and interfaces, as well as code snippets to illustrate these concepts. Additionally, it discusses the significance of nested interfaces and the Object class in Java.

Uploaded by

Amogh B
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views15 pages

Java Module 3 Notes

The document covers various concepts of inheritance and interfaces in Java, including types of inheritance, method overriding, dynamic method dispatch, abstract classes, and the use of the final keyword. It provides definitions, examples, and comparisons of abstract classes and interfaces, as well as code snippets to illustrate these concepts. Additionally, it discusses the significance of nested interfaces and the Object class in Java.

Uploaded by

Amogh B
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 3

QUESTION AND ANSWERS

Inheritance: Inheritance Basics, Using super,


Creating a Multilevel Hierarchy, When Constructors Are Executed in multilevel Hierarchy,
Method Overriding, Dynamic Method Dispatch,
Using Abstract Classes, Using final with Inheritance
Local Variable Type Inference and Inheritance,
The Object Class. Interfaces: Interfaces,
Default Interface Methods,
Use static Methods in an Interface,
Private Interface Methods.

1. Define inheritance and list the different types of inheritance in Java.


Inheritance is the feature of Object Oriented Programming in which one class can inherit properties and
methods of another class. A class from which another class inherits is called parent class, base class or
super class. A class which inherits properties and methods of another class is called child class or derived
class or sub class.

Advantage : Code reusablity is achieved through inheritance.

Types of Inheritance

Single Inheritance
A class inherits from one superclass only.

Multilevel Inheritance:
A class is derived from another class, which is also derived from another class.

Multiple Inheritance
A Class can inherit from more than one class.

Hierarchical Inheritance
More than one class inheriting from one class.

Hybrid Inheritance
A combination of one or more types of inheritance.

Java does not support multiple inheritance and hybrid inheritance.


Child class cannot access private data members and private methods of parent class.
2. Explain how superclass variable can reference subclass object.

A super class variable can be assigned a reference to any of its subclass. Type of reference variable
and not type of object it refers determines what members can be accessed.

Example:

class parentclass {
public void parentClassMethod()
{
[Link]("Parent class method ");
}
public void display()
{

[Link]("Display of Parent class ");


}

class childclass extends parentclass{

public void childClassMethod()


{
[Link]("Parent class method ");
}
// overrides parent class display method
public void display()
{

[Link]("Display of child class ");


}
}

class InheritanceDemo {
public static void main(String args[])
{
parentclass obj1 = new childclass();

[Link]();
//[Link](); // error - because obj1 is parent class reference
//variable and accessing child class methods or
// data members.
[Link]();
}
}

Output :

Parent class method


Display of child class

3. Explain the order of constructor execution in a multilevel class hierarchy.

class A {
A()
{

[Link]("Constructor of A ");
}

class B extends A {
B()
{
[Link]("Constructor of B ");
}

class C extends B {
C()
{

[Link]("Constructor of C ");
}

}
class SuperDemo1 {
public static void main(String args[])
{
C obj = new C();
}
}

Output:

Constructor of A
Constructor of B
Constructor of C

4. Illustrate usage of super keyword in Java with suitable example.


‘super’ keyword in Java is used to
 Call the constructor of immediate super class.
 Access the data members and methods of immediate super class whenever there
is name clash

Using super keyword to call constructor of immediate parent class

Example:

class A {
int a1;
A(int x)
{
a1 = x;
[Link]("Constructor of A with a1 value " + a1);
}

class B extends A {
int b1;
B(int a1, int b1)
{
super(a1); // commenting this line leads to error
this.b1 = b1;
[Link]("Constructor of B with b1 value" + this.b1);
}

class SuperDemo2 {
public static void main(String args[])
{
B obj = new B(10,20);
}
}

Output :
Constructor of A with a1 value 10
Constructor of B with b1 value 20

Using super to access methods of immediate parent class:

class A {
int a1;
A()
{
a1 = 99;

}
public void display()
{
[Link]("value of a1 " + a1);
}

}
class B extends A {
int b1 ;
B()
{
b1 = 999;

public void display()


{
[Link](); // calls parent class (A) display method
[Link]("value of b1 " + b1);
}
}

class SuperDemo1 {
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}

Output :

value of a1 99
value of b1 999
5. Explain the dynamic method dispatch with example
Dynamic method dispatch is the feature in java which resolves at run time the call to overridden
method. This is also called run time polymorphism.

Example 1:
class Parent {
void display()
{
[Link]("Display in Parent");
}
}
class Child extends Parent{
void display()
{
[Link]("Display in Child");
}
}
public class Override1{
public static void main(String args[])
{
// obj is parent class reference variable pointing to child object
Parent obj = new Child();
// in following statement compiler checks if display function
// exists in parent class and gives error if it does not exist
// but calls display() of child class during execution.
[Link](); // calls display method in child class
}
}

Example 2:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}
public class TestDispatch {
public static void main(String[] args) {
Animal a; // Parent class reference

a = new Dog(); // Dog object


[Link](); // Outputs: Dog barks

a = new Cat(); // Cat object


[Link](); // Outputs: Cat meows
}
}

Output :

Dog barks
Cat meows

Explanation :

 The reference variable ‘a’ is of type Animal.


 At runtime, Java determines the actual object it is assigned to (Dog or Cat) and calls the
appropriate sound() method.
 This is dynamic dispatch — the method call is resolved dynamically based on the actual
object.

6. Illustrate method overriding with an example.


When parent class and child class has method with same name and arguments, and when that method is called with
child class object, child class method is called (or overrides) and not parent class method.

Rules for method overriding

 A constructor cannot be overridden.


 Final - declared methods cannot be overridden.
 Any method that is static cannot be used to override.

Example :

class Parent {
void display()
{
[Link]("Display in Parent");
}
}

class Child extends Parent{


void display()
{
[Link]("Display in Child");
}
}

public class overridingDemo {

public static void main(String args[])


{
Parent p1 = new Parent(); // p1 is parent class reference variable and points to parent class object
Parent p2 = new Child(); // p2 is parent class reference variable and points to child class object
Child c2 = new Child(); // c2 is child class reference variable and points to child class object

// calls display method of parent class


[Link]();
// calls display method of Child class - overrides parent class display function
[Link]();
// calls display method of Child class - overrides parent class display function
[Link]();

}
}

Output :

Display in Parent
Display in Child
Display in Child

Why Overridden method :

Allows parent class to define a method that is common to all its child classes.

7. Compare and contrast method overloading and method overriding with


suitable example.

Feature Compile-time Polymorphism Runtime Polymorphism


Also known as Static binding, early binding, overloading Dynamic binding, late binding, overriding
Method resolution Determined by the compiler Determined during program execution
Implementation Method overloading, operator overloading Method overriding, virtual functions
Flexibility Less flexible, fixed at compile time More flexible and adaptable
Faster, as the method call is pre- Slower, due to the overhead of runtime
Execution speed
determined lookup
8. What is abstract class and abstract method? Illustrate with example.
Abstract method in java is a method in class which does not have body or which is not implemented. It is
implemented in child class.

Abstract class is one in which there is atleast one abstract method.

 Abstract class cannot be instantiated i.e. objects of abstract class cannot be


 created. But abstract class can be used to create references.
 Any class which has abstract method must be declared abstract.
 A constructor cannot be abstract.
 A static method cannot be abstract.
 A subclass of abstract class MUST COMPULSORILY define abstract methods in
superclass.

abstract class A {
int a1;
//abstract A() // compilation error - constructor cannot be abstract
//abstract static void method1() // compilation error - static method cannot be abstract
abstract void method1();
}
class B extends A {
void method1()
{
}
}
// error - in following class as class C does not define abstract method method1()
/*
class C extends A {

}
*/
class abstractDemo {
public static void main(String args[])
{
A obj = new A(); // compilation error - abstract class object cannot be created
A obj = new B(); // abstract class reference can be created
}
}

Example :

abstract class Shape2D {


double area;
double perimeter;
abstract void calculate();
void display()
{
[Link]("Area = " + area);
[Link]("Perimeter = " + perimeter);
}
}
class Rectangle extends Shape2D{
double length;
double breadth;
Rectangle(double l, double b)
{
[Link] = l;
[Link] = b;

}
void calculate()
{
area = length * breadth;
perimeter = 2.0 * (length + breadth);
}
void display()
{
[Link]("Length = " + length);
[Link]("Breadth = " + breadth);
[Link]();
}
}

class AbstractDemo {
public static void main(String args[])
{
Rectangle r1 = new Rectangle(3.0, 5.0);
[Link]();
[Link]();
}
}

9. List the different uses of final and demonstrate each with help of code
snippets.

Final keyword can be used with variable, method and class.

Final variable

A final variable can be assigned only once. Once set, its value cannot be changed.

Example :

public class FinalVariableExample {


public static void main(String[] args) {
final int MAX_USERS = 100;
// MAX_USERS = 200; // Compilation error: cannot assign a value to final variable
[Link]("Max users allowed: " + MAX_USERS);
}
}

Final Methods

A final method cannot be overridden by subclasses. This is useful for preserving behavior.

class Vehicle {
public final void startEngine() {
[Link]("Engine started");
}
}

class Car extends Vehicle {


// public void startEngine() {} // Compilation error: cannot override final method
}

Final Class

A final class cannot be subclassed. In other words, final class cannot become parent class. This is often
used for security or design reasons.

Example :

final class Parent {


public static void printMessage(String msg) {
[Link](msg);
}
}

// class Child extends Parent {} // Compilation error: cannot inherit final class

10. What is interface? Briefly explain the general form of an interface.

Interface is a class in Java which -

 cannot be instantiated but can be used to create references


 can have only final and static data members
 can have default methods, private methods, static methods and methods with
no implementations
 'implements' keyword is used to create subclass of interface
 multiple interfaces can be implemented
 one interface can extend another another interface
 methods that implement an interface must be declared public
 a class which does not implement all the methods of interface must be
declared abstract - partial implementations
 Top-level interface can be public or default - can be accessed by class
outside the package
 Nested-level interface can be public, protected, private or default

General form of interface :

access interface <interfacename> {


// final or static data members
<datatype> variablename = value;
// static methods, default methods, private methods
<return type> methodname(parameter list);
}

Example :

interface Shape2D {
final static float pi = 3.14f;
void compute();
}
class Circle implements Shape2D{
float radius;
float area;
Circle(float radius) {
[Link] = radius;
}
public void compute() {
area = pi * radius * radius;
}
void display() {
[Link]("Area of circle with radius " + radius + " is " + area);
}
}
class TestInterface {
public static void main(String[] args) {
Circle c1 = new Circle(7.0f);
[Link]();
[Link]();
}
}

output :
Area of circle with radius 7.0 is 153.86002
11. Discuss the significance of nested interface in Java.

Nested interface
An interface defined inside another class or another interface is called
nested interface or member interface. A nested interface can be private, public, protected
Nested interface must be fully qualified when accessed from outside.

Example :

class A {
public interface NestedIF {
boolean isNotNegative(int x);
}
}
class B implements [Link] {
public boolean isNotNegative(int x) {
if (x < 0)
return false;
else
return true;
}
}
class NestedIFDemo {
public static void main(String args[])
{
[Link] obj = new B();
int num = 10;
if ([Link](num))
[Link](num + "is Not negative");
else
[Link](num + " is negative");
}
}

12. Explain about Object class in java


Object class in Java part of the [Link] package and every class in Java either directly or indirectly
inherits from it.
Object class - is a java class which is superclass of all classes. Reference variable of Object class can refer
any class. The methods of class are :
toString()
getClass()
notify()
notifyAll()
wait()
Example 1:

class A {

}
class B {

}
class Demo3 {
public static void main(String args[])
{
A obj1 = new A();
B obj2 = new B();
[Link]([Link]());
[Link]([Link]());
}
}
Output :
class A
class B

Example 2:

class Person {
String name;
String qual;

public Person(String name, String qual) {


[Link] = name;
[Link] = qual;
}

@Override
public String toString() {
return "Person " + name + "," + qual;
}

public static void main(String[] args) {


Person p = new Person("Geetha", "MCA");
[Link](p); // toString() method is automatically called when object is printed

}
}
12. Compare and contrast Abstract class and Interface.

Abstract class Interface

Abstract class can have abstract methods and non An interface can have abstract methods, static and
abstract methods default methods.

Abstract class does not support multiple inheritance Interface supports multiple inheritance

Can have final, non-final, static and non static variables Can have only static and final variables

Abstract class can implement interface An interface cannot implement abstract class

abstract keyword is used to declare abstract class interface keyword is used to declare interface

Abstract class can extend abstract class and any other An interface can extend an interface only
class

“extends” keyword is used to extend abstract class “implements” keyword is used to implement interface

Programs

1. Build a Java program to create an interface Resizable with method resize (int radius) that allow an
object to be resized. Create a class circle that implements resizable interface and implements the
resize method.
2. Build a Java program to create a class named ‘Shape’. Create 3 sub classes namely circle, triangle
and square: each class 2 methods name draw() and erase(). Demonstrate polymorphism concepts
by developing suitable methods and main program.
3. Develop a Java program to create an abstract class Shape with abstract methods calculateArea()
and calculatePerimeter(). Create subclasses Circle andTriangle that extend the Shape class and
implement the respective methods to claculate the area and perimeter of each shape.

You might also like