Unit - II Inheritance, Interface and Packages

 Unit - II Inheritance, Interface and Packages 

2.1 Inheritance: concept of inheritance , types of Inheritance: single inheritance, multilevel inheritance, hierarchical inheritance, method overriding, final variables, final methods, use of super, abstract methods and classes

 2.2 Interfaces: Define interface, implementing interface, accessing interface variables and methods, extending interfaces

 2.3 Package: Define package, types of package, naming and creating package, accessing package, import statement, static import, adding class and interfaces to a package

2.1 Inheritance: concept of inheritance , types of Inheritance: single inheritance, multilevel inheritance, hierarchical inheritance, method overriding, final variables, final methods, use of super, abstract methods and classes

Inheritance (Concept)

  • Inheritance is a mechanism in Java where one class acquires the properties and behaviors of another class.

  • It promotes code reusability by allowing a child class to reuse the fields and methods of a parent class.

  • The extends keyword is used to create a subclass from a superclass.

  • Inheritance supports hierarchical relationships between classes in object-oriented programming.

  • A derived class can add its own members while also using the parent class members.

  • It helps in implementing real-world relationships and supports polymorphism.

Syntax:
class Subclass extends Superclass { }

Example:

class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } public static void main(String[] args) { Dog d = new Dog(); d.sound(); d.bark(); } }

Single Inheritance

  • In single inheritance, one subclass inherits from a single parent class.

  • It is the simplest form of inheritance in Java.

  • The subclass can access all non-private members of the parent class.

  • It helps eliminate redundant code by reusing parent class methods.

  • Only one level of class hierarchy is involved.

  • Single inheritance is the most commonly used inheritance in Java.

Syntax:
class Child extends Parent { }

Example:

class Vehicle { void start() { System.out.println("Vehicle starts"); } } class Car extends Vehicle { void drive() { System.out.println("Car is driving"); } public static void main(String[] args) { Car c = new Car(); c.start(); c.drive(); } }

Multilevel Inheritance

  • In multilevel inheritance, a class inherits from a class which is already a subclass of another class.

  • It creates a chain of inheritance from grandparent to parent to child.

  • The last derived class inherits features from both immediate and top-level parent classes.

  • It is useful when behavior needs to be passed through multiple levels.

  • Java supports multilevel inheritance using the extends keyword.

  • It helps in deepening the hierarchy to reflect real-world models.

Syntax:
class C extends B
class B extends A

Example:

class Grandparent { void show1() { System.out.println("Grandparent method"); } } class Parent extends Grandparent { void show2() { System.out.println("Parent method"); } } class Child extends Parent { void show3() { System.out.println("Child method"); } public static void main(String[] args) { Child c = new Child(); c.show1(); c.show2(); c.show3(); } }

Hierarchical Inheritance

  • In hierarchical inheritance, multiple subclasses inherit from a single superclass.

  • Each subclass inherits common features from the parent and adds its own.

  • It helps avoid duplication by placing shared code in the superclass.

  • All child classes are treated independently even though they share the same parent.

  • Java supports hierarchical inheritance as long as no multiple class extensions are used.

  • It supports better organization and structure of code.

Syntax:
class Aclass B extends A, class C extends A

Example:

class Shape { void draw() { System.out.println("Drawing shape"); } } class Circle extends Shape { void displayCircle() { System.out.println("Circle drawn"); } } class Square extends Shape { void displaySquare() { System.out.println("Square drawn"); } public static void main(String[] args) { Circle c = new Circle(); Square s = new Square(); c.draw(); c.displayCircle(); s.draw(); s.displaySquare(); } }

Method Overriding

  • In Java, method overriding allows a subclass to redefine a method already present in the parent class.

  • It is used to provide specific implementations of a method defined in a superclass.

  • The method name, return type, and parameters must be exactly the same as the parent class method.

  • It supports runtime polymorphism through dynamic method dispatch.

  • Only inherited methods can be overridden; static, private, or final methods cannot be overridden.

  • The @Override annotation is used to indicate method overriding explicitly.

Syntax:

class Parent { void display() { } } class Child extends Parent { @Override void display() { } }

Example:

class Parent { void greet() { System.out.println("Hello from Parent"); } } class Child extends Parent { void greet() { System.out.println("Hello from Child"); } public static void main(String[] args) { Child c = new Child(); c.greet(); } }

Final Variables

  • In Java, a final variable is a constant, and its value cannot be changed once assigned.

  • Final variables must be initialized during declaration or inside the constructor.

  • They help in defining constants like PI, MAX_SPEED, etc.

  • Final variables enhance code security by preventing accidental modification.

  • Final keyword can be used with variables, methods, and classes.

  • Once assigned, their values remain fixed for the lifetime of the program.

Syntax:

final int VALUE = 100;

Example:


class Demo { final int MAX = 50; void show() { System.out.println("Max value: " + MAX); } public static void main(String[] args) { Demo d = new Demo(); d.show(); } }

Final Methods

  • A final method in Java cannot be overridden by subclasses.

  • It is used to prevent modification of important logic.

  • Final methods provide consistent behavior and security.

  • They are inherited but not redefined.

  • Can be used for utility methods or sensitive calculations.

  • Improves reliability by locking method definitions.

Syntax:

final void show() { }

Example:

class Base { final void run() { System.out.println("Running safely"); } } class Derived extends Base { public static void main(String[] args) { Derived d = new Derived(); d.run(); } }

Use of super

  • super keyword is used in Java to refer to immediate parent class members.

  • It can be used to call parent constructors or access overridden methods.

  • super() must be the first statement in a child class constructor if used.

  • Helps avoid ambiguity when parent and child class have same variable/method names.

  • Supports constructor chaining in inheritance.

  • Useful for extending functionality while retaining parent behavior.

Syntax:

super.methodName();

Example:

class A { void show() { System.out.println("Inside A"); } } class B extends A { void show() { super.show(); System.out.println("Inside B"); } public static void main(String[] args) { B obj = new B(); obj.show(); } }

Abstract Classes

  • Abstract classes in Java are declared using the abstract keyword and cannot be instantiated.

  • They may contain both abstract methods (without body) and concrete methods.

  • Used to provide a base class with common properties or functionality.

  • Abstract classes serve as templates for their subclasses.

  • Subclasses must implement all abstract methods unless they are also abstract.

  • They support inheritance and partial abstraction.

Syntax:

abstract class ClassName { }

Example:

abstract class Vehicle { abstract void start(); void stop() { System.out.println("Vehicle stopped"); } } class Bike extends Vehicle { void start() { System.out.println("Bike started"); } public static void main(String[] args) { Bike b = new Bike(); b.start(); b.stop(); } }

Abstract Methods

  • An abstract method has no body and ends with a semicolon.

  • It must be declared inside an abstract class.

  • Subclasses are forced to provide implementations for abstract methods.

  • Helps in achieving abstraction and enforcing uniform method structure.

  • Cannot be final, static, or private.

  • Promotes a contract-based design in class hierarchies.

Syntax:

abstract void methodName();

Example:

abstract class Animal { abstract void makeSound(); } class Dog extends Animal { void makeSound() { System.out.println("Dog barks"); } public static void main(String[] args) { Dog d = new Dog(); d.makeSound(); } }

Interfaces in Java

  • An interface in Java is a collection of abstract methods and static/final variables declared using the interface keyword.

  • Interfaces are used to achieve 100% abstraction and define a contract that implementing classes must follow.

  • A class uses the implements keyword to provide definitions for the methods declared in the interface.

  • Variables declared in an interface are implicitly public, static, and final.

  • A class can implement multiple interfaces, supporting multiple inheritance in Java.

  • Interfaces can be extended using the extends keyword by another interface to build complex contracts.


Define Interface

Syntax:

interface InterfaceName { void method1(); int CONSTANT = 10; }

Example:

interface Printable { void print(); }

Implementing Interface

Syntax:


class ClassName implements InterfaceName { public void method1() { // method definition } }

Example:

interface Drawable { void draw(); } class Circle implements Drawable { public void draw() { System.out.println("Drawing Circle"); } public static void main(String[] args) { Circle c = new Circle(); c.draw(); } }

Accessing Interface Variables and Methods

  • Interface variables are accessed using the interface name.

  • Since they are static and final, they cannot be modified.

Syntax:

InterfaceName.VARIABLE;

Example:

interface Details { int MAX = 100; } class Show implements Details { public static void main(String[] args) { System.out.println("Max value: " + Details.MAX); } }

Extending Interfaces

  • One interface can inherit another interface using extends.

  • A single interface can extend multiple interfaces (multiple inheritance).

Syntax:

interface A { void methodA(); } interface B extends A { void methodB(); }

Example:

interface A { void display(); } interface B extends A { void show(); } class Demo implements B { public void display() { System.out.println("Display from A"); } public void show() { System.out.println("Show from B"); } public static void main(String[] args) { Demo d = new Demo(); d.display(); d.show(); } }

2.3 Package: Define package, types of package,naming and creating package, accessing package,
import statement, static import, adding class andinterfaces to a package

Packages in Java

  • A package in Java is a namespace that organizes classes and interfaces into a structured directory.

  • Packages help avoid class name conflicts and control access using visibility modifiers.

  • There are two types of packages: built-in packages (like java.util, java.io) and user-defined packages.

  • You can create your own package using the package keyword and store related classes together.

  • To use classes from another package, Java provides import and static import statements.

  • Packages allow grouping of classes, interfaces, and sub-packages, making application development more modular and manageable.


Define Package

Syntax:

package mypackage; public class MyClass { void display() { System.out.println("Inside package"); } }

Types of Package

  1. Built-in packages: Provided by Java (e.g., java.util, java.io;

  2. User-defined packages: Created by programmers to group related classes


Naming and Creating Package

Syntax:

// In file MyClass.java package mypack; public class MyClass { public void show() { System.out.println("MyClass in mypack"); } }

Steps to compile and run:


javac MyClass.java java mypack.MyClass

Accessing Package

  • Use import to access a class or all classes from a package.

Syntax:

import mypack.MyClass; // or import mypack.*;

Example:

// In another file import mypack.MyClass; class Test { public static void main(String[] args) { MyClass obj = new MyClass(); obj.show(); } }

Import Statement

  • Import statement is used to bring in classes and interfaces from other packages.

Syntax:

import package_name.ClassName; import package_name.*;

Static Import

  • Static import allows calling static members directly without class name.

Syntax:

import static java.lang.Math.*;

Example:

class Demo { public static void main(String[] args) { System.out.println(sqrt(25)); // No need to write Math.sqrt() } }

Adding Classes and Interfaces to a Package

  • Simply include multiple class or interface definitions in a file, or multiple files with the same package statement.

Syntax:

// In file A.java package mypack; public class A { } // In file B.java package mypack; public interface B { }














Comments

Popular posts from this blog

Syllabus

Unit VI: Interacting with Database

V. Java Networking