Notes Unit 4
Notes Unit 4
UNIT-4
INHERITANCE, PACKAGES AND INTERFACES
4.1 BASIC OF INHERITANCE
inheritance is a fundamental feature of object-oriented programming that allows you to create new classes
based on existing classes. The class that is being extended is called the superclass or parent class, and the
class that inherits from the superclass is called the subclass or child class. Inheritance promotes code reuse
and supports the concept of "is-a" relationship between classes.
To define a subclass and establish inheritance, you use the extends keyword in the class declaration. The
subclass inherits all the fields and methods (except for private members) of the superclass.
EXAMPLE:
// Superclass
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
}
// Subclass inheriting from Animal
class Dog extends Animal {
public Dog(String name) {
super(name); // Calling the superclass constructor
}
public void bark() {
System.out.println(name + " is barking."); } }
Key points to note about inheritance:
Subclasses can access non-private members (fields and methods) of the superclass.
Subclasses can add their own fields and methods or override the behaviour of the superclass
methods.
Constructors are not inherited but can be called using the super() keyword to invoke the superclass
constructor.
Java supports single inheritance, which means a class can only extend one superclass. However, it
allows for multiple levels of inheritance, where a subclass can itself become a superclass for another
subclass.
JAVA PROGRAMMING
EXAMPLE:
class Employee {
void salary() {
System.out.println("Salary= 200000");
}
}
class single_inheritance {
public static void main(String args[]) {
Programmer p = new Programmer();
p.salary(); // calls method of super class
p.bonus(); // calls method of sub class
}
}
JAVA PROGRAMMING
2.Multilevel Inheritance:
In multilevel inheritance, a subclass becomes the superclass for another subclass, creating a chain of
inheritance.
EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
JAVA PROGRAMMING
3.Hierarchical Inheritance:
In hierarchical inheritance, multiple subclasses extend a single superclass.
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();
}
}
JAVA PROGRAMMING
Method overriding allows you to provide specialized behaviour in subclasses while still adhering to the
common interface defined by the superclass. It is a powerful mechanism for achieving code reuse and
flexibility in object-oriented programming.
JAVA PROGRAMMING
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}
}
JAVA PROGRAMMING
2.Final Methods:
When a method is declared as final, it cannot be overridden by any subclass. This is useful when you want
to enforce a specific implementation of a method in a class hierarchy.
EXAMPLE:
class Bike{
final void run(){System.out.println("running"); }
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph"); }
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
3.Final Variables:
When a variable is declared as final, its value cannot be modified once it is assigned. It becomes a constant,
and the variable name is written in uppercase by convention.
EXAMPLE:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
The final keyword provides immutability, security, and performance benefits. By marking a class, method,
or variable as final, you can ensure that its behaviour cannot be modified or overridden, protecting critical
functionality or values.
It's important to note that using the final keyword should be done judiciously. Overusing it may limit the
flexibility and extensibility of your code, so it's recommended to use it when necessary, such as for
constants, non-over ridable methods, or classes that should not be subclassed.
JAVA PROGRAMMING
2.Abstract Methods:
An abstract method is declared using the abstract keyword and does not have an implementation.
Abstract methods are meant to be overridden by concrete subclasses.
Subclasses must provide an implementation for all the abstract methods inherited from the abstract
class.
Abstract methods do not have a body and end with a semicolon.
EXAMPLE:
abstract class Multiply
{
// abstract methods
// sub class must implement these methods
public abstract int MultiplyTwo (int n1, int n2);
public abstract int MultiplyThree (int n1, int n2, int n3);
// regular method with body
public void show() {
System.out.println ("Method of abstract class Multiply");
}
}
// Regular class extends abstract class
class AbstractMethodEx1 extends Multiply {
public int MultiplyTwo (int num1, int num2) {
return num1 * num2;
}
public int MultiplyThree (int num1, int num2, int num3) {
return num1 * num2 * num3;
}
// main method
public static void main (String args[]) {
Multiply obj = new AbstractMethodEx1();
System.out.println ("Multiplication of 2 numbers: " + obj.MultiplyTwo (10, 50));
System.out.println ("Multiplication of 3 numbers: " + obj.MultiplyThree (5, 8, 10));
obj.show();
}
}
JAVA PROGRAMMING
4.8 INTERFACE
Interfaces are useful for achieving abstraction, defining contracts, and enabling polymorphism. They provide
a way to define behaviour without specifying the implementation details, allowing for flexibility and code
reuse. They are widely used in Java to define APIs and ensure a consistent interface across different classes.
EXAMPLE:
interface In1 {
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
JAVA PROGRAMMING
// Print statement
System.out.println("Default API");
}
}
// Interface 2
// Extending the above interface
interface Interface1 extends API
{
// Abstract method
void display();
}
// Interface 3
// Extending the above interface
interface Interface2 extends API
{
// Abstract method
void print();
}
// Main class
// Implementation class code
class TestClass implements Interface1, Interface2
JAVA PROGRAMMING
{
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
4.9 PACKAGES
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
Providing controlled access: protected and default have package level access control. A protected
member is accessible by classes in the same package and its subclasses. A default member (without
any access specifier) is accessible by classes in the same package only.
Packages can be considered as data encapsulation (or data-hiding).
Types of packages:
1. Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly
used built-in packages are:
1 java.lang
2 java.io
3 java.util
4 java.applet
5 java.awt
6 java.net
JAVA PROGRAMMING
2.User-defined packages
These are the packages that are defined by the user. First we create a directory myPackage (name should be
same as the name of the package). Then create the MyClass inside the directory with the first statement
being the package names.
package access modifiers
EXAMPLE:
package mypackage;