0% found this document useful (0 votes)
13 views

unit 22

Uploaded by

s.hemaswathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

unit 22

Uploaded by

s.hemaswathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT II: Inheritance, Packages and Interfaces

2.1 Basic concepts of Inheritance


 Inheritance is a fundamental concept in object-oriented programming, enabling the
creation of hierarchical class structures.
 A general class (superclass) defines common traits, while specific classes (subclasses)
inherit these traits and add their unique features.
 Superclass: The class being inherited.
 Subclass: The class that inherits the superclass. It is a specialized version of the
superclass.

How Inheritance Works:

 The keyword extends is used to inherit a class.


 A subclass inherits all members (fields and methods) of its superclass.
 Subclasses can add their own unique members and methods.

// Create a superclass.

class A {

int i, j;

void showij() {

System.out.println("i and j: " + i + " " + j);

// Create a subclass by extending class A.

class B extends A {

int k;

void showk() {

System.out.println("k: " + k);

void sum() {
System.out.println("i+j+k: " + (i+j+k));

class SimpleInheritance {

public static void main(String args[]) {

A superOb = new A();

B subOb = new B();

// The superclass can be used independently.

superOb.i = 10;

superOb.j = 20;

System.out.println("Contents of superOb: ");

superOb.showij();

System.out.println();

// The subclass has access to all public members of its superclass.

subOb.i = 7;

subOb.j = 8;

subOb.k = 9;

System.out.println("Contents of subOb: ");

subOb.showij();

subOb.showk();

System.out.println("Sum of i, j, and k in subOb:");

subOb.sum();

Output:

Contents of superOb:
i and j: 10 20

Contents of subOb:

i and j: 7 8

k: 9

Sum of i, j and k in subOb:

i+j+k: 24

2.2. Types of inheritance

1. Single Inheritance

 In single inheritance, a subclass inherits from only one superclass. This is the simplest
form of inheritance, allowing a class to derive its properties and behaviors from a single
base class.

Program:

class A {
void display() {
System.out.println("Class A");
}
}
class B extends A {
void show() {
System.out.println("Class B");
}
}

public class Main {


public static void main(String[] args) {
B obj = new B();
obj.display(); // Output: Class A
obj.show(); // Output: Class B
}
}

Output:

Class A
Class B

Explanation:

 Class B inherits from Class A. This allows obj, an instance of Class B, to call the
display() method from Class A and the show() method from Class B. This
demonstrates a simple one-to-one inheritance relationship.

2. Multilevel Inheritance

 In multilevel inheritance, a class is derived from another class, which is itself derived
from another class. This forms a chain of inheritance.

Program:

class A {
void display() {
System.out.println("Class A");
}
}

class B extends A {
void show() {
System.out.println("Class B");
}
}

class C extends B {
void print() {
System.out.println("Class C");
}
}

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.display(); // Output: Class A
obj.show(); // Output: Class B
obj.print(); // Output: Class C
}
}
Output:

Class A
Class B
Class C

Explanation:

 Class C inherits from Class B, which in turn inherits from Class A. This multilevel
inheritance allows obj, an instance of Class C, to access methods from all classes in the
inheritance chain.

3. Multiple Inheritance (Not directly supported in Java, but can be achieved


using interfaces)

Definition:

 Multiple inheritance occurs when a class inherits from more than one class. Java does not
support multiple inheritance with classes to avoid ambiguity, but it can be achieved using
interfaces.

Program:

interface A {
void display();
}

interface B {
void show();
}

class C implements A, B {
public void display() {
System.out.println("Interface A");
}

public void show() {


System.out.println("Interface B");
}
}

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.display(); // Output: Interface A
obj.show(); // Output: Interface B
}
}

Output:

Interface A
Interface B

Explanation:
 Class C implements both interfaces A and B, allowing it to inherit methods from both.
This demonstrates how multiple inheritance can be achieved using interfaces in Java.

4. Hierarchical Inheritance

Definition:

 Hierarchical inheritance occurs when multiple classes inherit from a single superclass.

Program:

class A {
void display() {
System.out.println("Class A");
}
}

class B extends A {
void show() {
System.out.println("Class B");
}
}

class C extends A {
void print() {
System.out.println("Class C");
}
}

public class Main {


public static void main(String[] args) {
B obj1 = new B();
C obj2 = new C();
obj1.display(); // Output: Class A
obj1.show(); // Output: Class B
obj2.display(); // Output: Class A
obj2.print(); // Output: Class C
}
}

Output:

Class A
Class B
Class A
Class C

Explanation:

 Class B and Class C both inherit from Class A. This allows both obj1 (an instance of
Class B) and obj2 (an instance of Class C) to access the display() method from
Class A while having their own specific methods.

5. Hybrid Inheritance (Not directly supported in Java, but can be achieved using
interfaces)

Definition:
 Hybrid inheritance is a combination of two or more types of inheritance (e.g., multilevel
and multiple inheritance). Java does not support hybrid inheritance with classes but
allows it with interfaces.

Program:

interface A {
void display();
}

interface C {
void print();
}

class B {
void show() {
System.out.println("Class B");
}
}

class D extends B implements A, C {


public void display() {
System.out.println("Interface A");
}

public void print() {


System.out.println("Interface C");
}
}

public class Main {


public static void main(String[] args) {
D obj = new D();
obj.display(); // Output: Interface A
obj.show(); // Output: Class B
obj.print(); // Output: Interface C
}
}

Output:

- **Class D** inherits from **Class B** and implements interfaces `A` and
`C`, demonstrating a hybrid inheritance scenario where multiple types of
inheritance are combined. `obj`, an instance of `Class D`, can access methods
from its superclass and interfaces.

---

This comprehensive guide covers the different types of inheritance in Java


with relevant examp

2.3 Member Access and Inheritance


 Inheritance allows a subclass to inherit all members (fields and methods) of its superclass.
However, access to these members depends on their access modifiers (e.g., private, public,
protected).
 Members declared as private in the superclass are not accessible by the subclass.

Access Modifiers and Inheritance:


 private members: Only accessible within the class they are declared in. Subclasses
cannot directly access private members of the superclass.
 public members: Accessible from any other class, including subclasses.
 protected members: Accessible within the same package and by subclasses, even if
they are in different packages.
 default (package-private) members: Accessible only within the same package.

// Create a superclass.
class A {
int i; // public by default (package-private)
private int j; // private to class A

void setij(int x, int y) {


i = x;
j = y;
}
}

// A's j is not accessible here.


class B extends A {
int total;

void sum() {
total = i + j; // ERROR: j is not accessible here
}
}

class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
Output:
Error: j has private access in A

2.4 Usage of this and Super key word


Using This keyword
 In any method of a class, this refers to the current instance of that class.
 When dealing with inheritance, this still points to the current object, but it could be an
instance of a subclass if the object is of a derived type.
Program:
class Parent {
void show() {
System.out.println("Parent class");
}
}
class Child extends Parent {
void show() {
System.out.println("Child class");
}
Output: Child class
void callParentShow() {
// Calls the show method of the current class (Child)
this.show();
}
}
Explanation:
this.show() inside the callParentShow() method calls the show() method of the current class
(Child), not the superclass (Parent). This is because this refers to the current instance of Child,
and Java uses method overriding to call the most specific implementation of show(). Therefore,
the output is "Child class".

Using Super key word


• In Java, the super keyword is used to refer to the superclass of the current object.
Two primary uses of super:
• super in Constructors: Used to call a superclass constructor to initialize inherited fields.
• super for Members: Used to access or invoke hidden or overridden members of the
superclass

1. super in Constructors Program:

class Parent {
void show() {
System.out.println("Parent class");
}
}
class Child extends Parent {
void show() {
System.out.println("Child class");
}

void callParentShow() {
// Calls the show method of the parent class (Parent)
super.show();
}
}
Output
Parent class
Explanation:
In the callParentShow() method of the Child class, super.show() calls the show() method
from the Parent class, bypassing the overridden method in Child. This is because super
refers to the superclass (Parent), so the output is "Parent class"
2. Accessing Superclass Members
To access fields or methods from the superclass that are hidden or overridden by the subclass.
This is useful when a subclass defines a member with the same name as one in the superclass.
Syntax: super.memberName;/super.methodName();
class Box {
double width, height, depth;
void displayDimensions() {
System.out.println("Width: " + width + ", Height: " + height + ", Depth: " + depth);
}
}
class BoxWeight extends Box {
double weight;
void displayDimensions() {
super.displayDimensions(); // Calls the displayDimensions() method from Box
System.out.println("Weight: " + weight);
}
}
Explanation:
In the BoxWeight class, the displayDimensions() method first calls super.displayDimensions() to
execute the displayDimensions() method from the Box class, which prints the width, height, and
depth. After that, it prints the weight specific to BoxWeight. This demonstrates how super is
used to call a superclass method from a subclass and then extend or enhance its functionality
2.5 Method Overriding
• In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the superclass.
• When an overridden method is called from within its subclass, it will always refer to the
version of that method defined by the subclass. The version of the method defined by
the superclass will be hidden.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k); Output:
} k: 3
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Explanation:
In the B class, the show() method overrides the show() method from the A class. When
subOb.show() is called, it invokes the overridden show() method in B, which prints the value of
k rather than the values of i and j from A. This demonstrates method overriding where the
subclass (B) provides a specific implementation of a method that was defined in its superclass
(A).
2.6 Method Overloading
Definition: Method overloading in Java allows a class to have more than one method with the
same name but different parameters. The methods can differ by the number of parameters, types
of parameters, or both. It is a way to increase the readability of the program and to use the same
method name for methods that perform similar functions but with different types or numbers of
inputs.
class OverloadExample {
// Method with no parameters
void display() {
System.out.println("No parameters");
}

// Method with one int parameter


void display(int a) {
System.out.println("Integer parameter: " + a);
}

// Method with two int parameters


void display(int a, int b) {
System.out.println("Two integer parameters: " + a + ", " + b);
}

// Method with one double parameter Output:


void display(double a) { No parameters
System.out.println("Double parameter: " + a); Integer parameter: 10
} Two integer parameters: 10, 20
} Double parameter: 10.5
public class Main {
public static void main(String[] args) {
OverloadExample obj = new OverloadExample();

obj.display(); // Output: No parameters


obj.display(10); // Output: Integer parameter: 10
obj.display(10, 20); // Output: Two integer parameters: 10, 20
obj.display(10.5); // Output: Double parameter: 10.5
}
}
Explanation:
Method overloading allows multiple display() methods in the OverloadExample class, each with
different parameter lists. When display() is called, Java determines which version to execute
based on the arguments passed. This provides flexibility and improves code readability by using
the same method name for similar actions with different inputs.
2.7 Abstract classes & Methods
• It is a class that cannot be instantiated directly.
• It can have both complete (concrete) methods and incomplete (abstract) methods.
• To provide a base or template for other classes.
• It defines common characteristics but leaves some details to be implemented by
subclasses.
Abstract Method:
• It is a method that is declared without an implementation (no body). It only has a method
signature (name, parameters, and return type).
• To ensure that all subclasses provide their own specific implementation of this method.
Program:
abstract class A
{
abstract void callme(); // Abstract methods
void callmetoo() // Concrete methods are still allowed in abstract classes
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}
Explantion:
 Abstract Class A: Contains an abstract method callme() that must be implemented by
subclasses and a concrete method callmetoo() that provides a default implementation.
 Class B: Extends abstract class A and provides an implementation for the callme() method. It
inherits callmetoo() as is from A.
 AbstractDemo Class: Creates an instance of B and calls both callme() (implemented in B)
and callmetoo() (inherited from A).
2.7 Dynamic Method Dispatch
• It is a feature in Java that determines which version of an overridden method to call at
runtime (when the program is running), not at compile time (when the code is being
compiled).
How It Works:
• A superclass reference variable can refer to objects of its subclass.
When you call an overridden method using this superclass reference, Java figures out which
subclass’s version of the method to execute based on the actual object that the reference is
pointing to, not the type of the reference itself
Program:

class A {

void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
Output:
// override callme()
void callme() { Inside A's callme method
System.out.println("Inside C's callme method");
} Inside B's callme method
}
Inside C's callme method
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}

Explanation:
 r is a reference of type A that can point to any object of type A, B, or C.
 The method callme() is dynamically dispatched based on the actual object that r points to:

 When r points to an A object, A's callme() is called.


 When r points to a B object, B's callme() is called.
 When r points to a C object, C's callme() is called.

2.8 Using final with Inheritance


Using final to Prevent Overriding
 To disallow a method from being overridden, specify final as a modifier at the start of its
declaration.
 Methods declared as final cannot be overridden.
Using final to Prevent Inheritance
• To precede the class declaration with final can prevent a class from being inherited.
• Declaring a class as final implicitly declares all of its methods as final, too.
Using final to Prevent Inheritance
• To precede the class declaration with final can prevent a class from being inherited.
• Declaring a class as final implicitly declares all of its methods as final, too
Using final to Prevent Overriding
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}}
Explanation:
Class A: Contains a method meth() declared as final. This means that meth() cannot be
changed or overridden by any subclass.
Class B: Attempts to override the meth() method. However, since meth() in class A is final,
this results in a compilation error. The error occurs because Java prevents subclass B from
altering the behavior of the final method inherited from class A.
Using final to Prevent Inheritance
final class A
{
//...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Explanation:
Class A: Declared as final. This means that no other class can extend or inherit from class A.
Class B: Attempts to extend class A. This is illegal and will result in a compilation error because
class A is final and cannot be subclassed.
2.9 Defining package
A package is a mechanism for organizing classes, interfaces, and sub-packages into namespaces.
It helps manage the namespace by grouping related classes and interfaces, preventing naming
conflicts, and controlling access.
For example, the java.util package contains utility classes like ArrayList, HashMap, etc.,
organizing them under the java.util namespace.
Defining a Package
To create a package is quite easy: simply include a package command as the first statement in a
Java source file. Any classes declared within that file will belong to the specified package. The
package statement defines a name space in which classes are stored. If you omit the package
statement, the class names are put into the default package, which has no name.
Syntax:
package pkg;
Here, pkg is the name of the package.
For example:
package MyPackage;
Package Hierarchies:
Java uses file system directories to store packages. For example, the .class files for any classes
you declare to be part of MyPackage must be stored in a directory called MyPackage. The
general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system.
For example, package java.awt.image;
A package needs to be stored in java\awt\image in a Windows environment. Be sure to choose
your package names carefully.
2.10 Access Protection
Public:
• Accessible from anywhere.
• Use when you want the class, method, or variable to be accessible by any other code.
Private:
• Accessible only within the same class.
Use to hide details from all other classes, ensuring encapsulation
Default (Package-Private):
• No explicit modifier.
• Accessible within the same package.
• Visible to subclasses and other classes in the same package, but not outside the package.
Program:

package mypackage;
class MyClassA {
void displayMessage() {
System.out.println("Hello from MyClassA!");
}
}
public class MyClassB {
public static void main(String[] args) {
MyClassA obj = new MyClassA(); // Accessible because both are in the same package
obj.displayMessage(); // Accessible because method has package-private access
}
}
Attempting Access from Another Package
package anotherpackage;
import mypackage.MyClassA;
public class MyClassC {
public static void main(String[] args) {
MyClassA obj = new MyClassA(); // Compilation error: MyClassA is not public in
mypackage
obj.displayMessage(); // Compilation error: displayMessage() has package-private
access
}
}
Protected
• Accessible within the same package and by subclasses even if they are in different
packages.
• Use when you want to allow access to subclasses while restricting access from non-
subclasses outside the package.
package mypackage;
public class ParentClass {
protected void protectedMethod() {
System.out.println("Protected method in ParentClass");
}
}
package mypackage;
public class ChildClass extends ParentClass {
public void accessProtectedMethod() {
protectedMethod(); // Accessible because ChildClass is a subclass
}
}
package testpackage;
import mypackage.ParentClass;
public class TestClass {
public static void main(String[] args) {
ParentClass obj = new ParentClass();
// obj.protectedMethod(); // Compilation error: protectedMethod() has protected access
in ParentClass
}
}
2.11 Importing Packages
• Allows referring to classes directly by their names after import.
Syntax:
import pkg1[.pkg2].(classname | *);
pkg1: Top-level package name.
pkg2: Subordinate package (optional).
classname: Specific class to import.
*: Imports all classes from the package

Example: import java.util.Date;


// Imports a specific class.
import java.io.*;
// Imports all classes from java.io package.
Implicit Imports:
• java.lang is implicitly imported by the Java compiler.
• Equivalent to import java.lang.*; at the top of every program.
2.12 Defining interfaces
• Using the keyword interface, you can fully abstract a class’ interface from its implementation.
• That is, using interface, specify what a class must do, but not how it does it.
• Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
• Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
Syntax:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Example:
interface Callback
{
void callback(int param);
}
2.13 Implementing interfaces
• To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface
Syntax:
class classname [extends superclass][implements interface]
{
// class-body
}
Example:
class Client implements Callback
{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
callback( ) is declared using the public access modifier
• It is both permissible and common for classes that implement interfaces to define additional
members of their own
class Client implements Callback
{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
void nonIfaceMeth()
{
System.out.println("Classes that implement interfaces" +
"may also define other members, too.");
}
}
2.14 Extending interfaces.
• One interface can inherit another by use of the keyword extends.

Program:
// One interface can extend another.
interface A
{
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
} Output:
public void meth3() {
System.out.println("Implement meth3()."); Implement meth1().
}
} Implement meth2().

class IFExtend
Implement meth3().
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Explanation:

 Interface A defines two methods: meth1() and meth2().


 Interface B extends A and adds a third method: meth3().
 Class MyClass implements B, so it must provide implementations for all three methods
(meth1(), meth2(), and meth3()).
 In the main method, an instance of MyClass is created, and all three methods are called,
printing their respective messages.

You might also like