unit 22
unit 22
// Create a superclass.
class A {
int i, j;
void showij() {
class B extends A {
int k;
void showk() {
void sum() {
System.out.println("i+j+k: " + (i+j+k));
class SimpleInheritance {
superOb.i = 10;
superOb.j = 20;
superOb.showij();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
subOb.showij();
subOb.showk();
subOb.sum();
Output:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
i+j+k: 24
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");
}
}
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");
}
}
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.
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");
}
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");
}
}
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");
}
}
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.
---
// Create a superclass.
class A {
int i; // public by default (package-private)
private int j; // private to class A
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
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");
}
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:
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
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: