Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

UNIT 2 Inheritance Packages Interfaces

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

RAMCO INSTITUTE OF TECHNOLOGY

Department of Information Technology


Academic Year: 2023 – 2024 (Odd Semester)

CS3391 & Object-Oriented Programming

Unit II – INHERITANCE, PACKAGES AND INTERFACES (8+1 SKILL) 9

Overloading Methods-Objects as Parameters-Returning Objects-Static, Nested and Inner Classes.


Inheritance: Basics-Types of Inheritance-Super keyword-Method Overriding -Dynamic Method
Dispatch-Abstract Classes-final with Inheritance. Packages and Interfaces: Packages-Packages and
Member Access -Importing Packages – Interfaces.

Overloading Methods
When a class has more than one method having the same name but with different parameter lists,
this feature is called method overloading in Java.
There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Java Program: (Method Overloading by changing number of arguments)

class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

OUTPUT:

22

33

Java Program: (Method Overloading by changing data type of arguments)

In this example, two methods were created that differs in data type. The first add method receives two
integer arguments and second add method receives two double arguments.

class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

OUTPUT:

22

24.9
Benefits of using Method Overloading

➢ Method overloading increases the readability of the program.

➢ Provides flexibility to call the same method for different types of data.

➢ This makes the code look clean.

➢ This reduces the execution time because the binding is done in compilation time itself.

➢ Method overloading minimises the complexity of the code.

➢ use the code again, which saves memory.

Objects as Parameters

Like primitive types, Objects can be passed as parameters to methods in Java. When passing
an object as a parameter to a method, a reference to the object is passed rather than a copy of the
object itself. This means that any modifications made to the object within the method will have an
impact on the original object.

Java objects as parameters example

public class MyClass


{
private int attribute1;
private String attribute2;
private double attribute3;
// Constructor
public MyClass(int attribute1, String attribute2, double attribute3)
{
this.attribute1 = attribute1;
this.attribute2 = attribute2;
this.attribute3 = attribute3;
}
// Method with object as parameter
public void myMethod(MyClass obj)
{
System.out.println("Attribute 1: " + obj.attribute1);
System.out.println("Attribute 2: " + obj.attribute2);
System.out.println("Attribute 3: " + obj.attribute3);
}
public static void main(String[] args)
{
MyClass myObject1 = new MyClass(10, "Hello", 3.14);
MyClass myObject2 = new MyClass(20, "World", 6.28);
// Call the method with object as parameter
myObject1.myMethod(myObject2);
}
}
Output:

Attribute 1: 20

Attribute 2: World

Attribute 3: 6.28

The class MyClass in this code has three attributes labeled attribute1, attribute2, and
attribute3 and a constructor that accepts three parameters. The class also includes a method called
myMethod, which accepts as a parameter an object of the same class MyClass. The attributes of the
passed object are printed using System.out.println() statements within the method. In the main()
method, two MyClass objects are constructed using the constructor, and then the myMethod()
method of the first object is invoked with the second object as a parameter. This results in the output
of the attributes of the second object to the console.

Returning Objects:

A method can have the class name as its return type. Therefore it must return the object of
the exact class or its subclass.

Java methods can also return objects. A reference to the object is returned when an object is
returned from a method, and the calling method can use that reference to access the object.

class SumReturn
{
private int a;
public SumReturn(int i)
{
a = i;
}
/*The addition method returns a SumReturn object with adding 100 into it. */
public SumReturn addition()
{
SumReturn result = new SumReturn(a + 100);

return result;
}
public void display()
{
System.out.println("Additon result: " + a);
}
}
public class SampleReturn3
{
/* Driver Code */
public static void main(String[] args)
{
SumReturn obj1 = new SumReturn(50);
SumReturn obj2;
/* addition method returns a reference of SumReult class */
obj2 = obj1.addition();
obj2.display();
}
}

Output:

Addition result: 150

In the above code, a SumResult class contains an addition method with class name as its return type.
It returns the result value and prints it using the display method.

Static, Nested and Inner Class:

In Java, static is one of the most popular keywords associated with methods, variables, classes,
and blocks.

Static class in Java is a nested class and it doesn't need the reference of the outer class. Static
class can access only the static members of its outer class.
Syntax:

class Outer

static class Nested

1. Inner Class
Inner class is a class that is declared inside the class or interface and can access all the
members of the outer class including private data members and methods
2. Outer Class

Outer classes are the classes in which nested or inner classes are defined.

3. Nested Class
➢ Nested class can be static or non-static. The non-static nested class is known as an inner
class.

➢ An instance of a static nested class can be created without the instance of the outer
class.

➢ The static member of the outer class can be accessed only by the static nested class.

The following figure illustrates the inner, outer, and nested classes.

➢ The nested static class can access the static variables.

➢ Static nested classes do not have access to other members of the enclosing class which
means it has no access to the instance variables (non-static variables) which are
declared in the outer class.

Class Outer
{
// static member of the outer class
private static char grade=’A’;
// static class
static class Nested
{
public void fun()
{
//nested class can access the static members of the outer class
System.out.println(“Grade:”+grade);
}
}
Public static void main(String args[])
{
Outer.Nested obj = new Outer.Nested(); // creating an object of nested class without
//creating an object of the outer class.
obj.fun();
}
}
Output: Grade: A

Difference between Static and Non-static Nested Class

➢ Static nested class can access the static members of the outer class and not the non-static
members, whereas non-static nested class, i.e., the inner class can access the static as well as
the non-static members of the outer class.
➢ An instance of the static nested class can be created without creating an instance of the outer
class.

The static keyword helps in memory management.

INHERITANCE BASICS:

➢ Inheritance is the process by which one object acquires the properties and behaviors of
another object. Inheritance provides code reusability and establishes relationships
between different classes.

➢ A class which inherits the properties is known as Child Class(sub-class or derived class)
whereas a class whose properties are inherited is known as Parent class(super-class or
base class).

➢ Besides, the child class may add its own attributes and methods and may modify any of
the super-class methods. Inheritance defines a “is – a” relationship.
➢ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.

➢ Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

Advantages of Inheritance:

➢ Code reusability and saves time

➢ With java inheritance, the parent class method overriding the child class is possible

Types of Inheritance:

Types of inheritance:

1. Single inheritance

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
Output:
barking…
Eating…

2. Multiple inheritance

When one class inherits multiple classes, it is known as multiple inheritance. In Java, multiple
inheritance is not supported through class but can be achieved through interfaces.

3. Mutilevel inheritance

A class which is derived from other derived class is called multilevel inheritance.

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();
}
}

Output:

weeping…

barking…

eating…

4. Hierarchical inheritance.
When two or more classes inherits from one super class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so
there is hierarchical inheritance.

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();

Output:
meowing…
eating….

Class hierarchy
A child class of one parent class can be the parent of another child class

Hybrid inheritance:
Hybrid inheritance is the composition of two or more types of inheritance. The main
purpose of using hybrid inheritance is to modularize the code into well-defined classes. It also
provides the code reusability.

Java supports hybrid inheritance by using the following combinations:

Single and Multiple Inheritance

- not supported but can be achieved through interface)

Multilevel and Hierarchical Inheritance

Hierarchical and Single Inheritance

Multiple and Multilevel Inheritance

Super Keyword:
The super keyword in Java refers to the immediate parent class reference. The Super Keyword
in Java is used to access the data members, methods as well as the constructor of the parent class.

The most important use of the Super Keyword in Java is to avoid ambiguity between the child
class and its parent class that has the same data members or methods.

Whenever the instance of subclass created, an instance of parent class also created implicitly
which is referred to by the super keyword in java.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

1. Java Program:(Refer immediate parent class variables)

//Parent class

class College
{
//Instance variable
int id;
String name = “ RAMCO INSTITUTE OF TECHNOLOGY”
}
class Student extends College
{
//Instance variable in the child class
int id;
String name= “Raj”;
void printStudentDetail()
{
//using super.name we can access the name variable of the Parent class
//using this.name we can access the name variable of the Parent class
System.out.println(“Student Name:”+this.name);
System.out.println(“College Name:”+super.name);
}
public static void main(String args[])
{
Student ob=new Student();
ob.printStudentDetail();
}
}
OUTPUT:

Student Name: Raj

College Name: Ramco Institute of Technology

2. Java Program:(Invoking immediate parent class method)

//Parent class

class College

//Instance variable

int id=101;

String name="RAMCO INSTITUTE OF TECHNOLOGY";

void printDetails()

System.out.println("College ID:"+this.id);

class Studentdemo extends College

//Instance variable in the child class

int id=301;

String name="Raj";

void printDetails()

//using super.name can access the name variable of the Parent class

//using this.name can access the name variable of the Parent class

System.out.println("Student Name:"+this.name);
System.out.println("Student ID:"+this.id);

System.out.println("College Name:"+super.name);

super.printDetails();

public static void main(String args[])

Studentdemo ob=new Studentdemo();

ob.printDetails();

Output:

Student Name: Raj

Student Id:301

College Name: RAMCO INSTITUTE OF TECHNOLOGY

College ID:101

3. Java Program:(To invoke immediate parent class constructor)

//Base class College

class College

College()

System.out.println("College class constructor");

//Derived class Student

class Student extends College


{

Student()

//Invoke the parent class constructor

super();

System.out.println("Student class constructor");

public static void main(String args[])

//Invoke the constructor of the Student class

Student s = new Student();

Output:

College class constructor

Student class constructor

Invoking parameterized parent class constructor:

In java it is possible to invoke the parameterized constructor of the parent class from the
subclass using the super keyword.

METHOD OVERRIDING

➢ Method overriding in Java refers to the ability of a subclass to provide a specific


implementation of a method that is already defined in its superclass. It allows a
subclass to modify the behavior of an inherited method from its superclass.

➢ Method overriding is an example of run-time polymorphism, dynamic or late binding.


It is also known as Dynamic Method Dispatch because the method that is going to be
called is decided at run time by the JVM.
Rules of Method Overriding

➢ Method overriding can only be implemented when two classes have an ‘is-a’
relationship of inheritance between them.

➢ The return type of the overridden method must be the same or covariant of the return
type of the superclass method.

Example Program:

class Train

public String accelerate(int mph)

return "The train accelerates at "+mph+"MPH";

public String start()

return "The train is running.";

public String stop()

return "The train has stopped.";

class BulletTrain extends Train

@Override

public String accelerate(int mph)

return "The bullet train accelerates at "+mph+"MPH.";

}
@Override

public String start()

return "The bullet train is running.";

@Override

public String stop()

return "The bullet train has stopped.";

public class Example

public static void main(String args[])

Train train=new Train();

String runTrain=train.start();

String accelerateTrain=train.accelerate(70);

String stopTrain=train.stop();

System.out.println(runTrain);

System.out.println(accelerateTrain);

System.out.println(stopTrain);

Train bulletTrain=new BulletTrain();

String runBulletTrain=bulletTrain.start();

String accelerateBulletTrain=bulletTrain.accelerate(310);

String stopBulletTrain=bulletTrain.stop();

System.out.println(runBulletTrain);

System.out.println(accelerateBulletTrain);

System.out.println(stopBulletTrain);

}
}

Explanation:

➢ The Train class is defined with three methods: accelerate(), start(), and stop(). Each method
returns a string representing the action performed.
➢ The BulletTrain class extends the Train class and overrides all three methods using
the @Override annotation. The overridden methods provide specialized implementations
for the BulletTrain class.
➢ The Example class contains the main() method, where instances of
both Train and BulletTrain are created and used to invoke the overridden methods.
➢ In the main() method, a Train object is created, and its start(), accelerate(),
and stop() methods are called. The output of these method invocations is printed.
➢ Next, a BulletTrain object is created and assigned to a Train reference. This demonstrates
polymorphism, as a subclass object can be assigned to a superclass reference.
➢ The overridden methods in the BulletTrain class are invoked using the bulletTrain reference.
The output of these method invocations is also printed.

Advantages of Method Overriding:

➢ It is used for the implementation of runtime or dynamic polymorphism.


➢ It is used to provide a specific implementation or definition of a method in a class, which is
already in an existence in its superclass.
➢ It is also used to define what behavior a class can have and how that behavior will be
implemented by the class that will inherits it.

DYNAMIC METHOD DISPATCH:

➢ Dynamic Method Dispatch in Java is the process by which a call to an overridden method
is resolved at runtime (during the code execution). The concept of method overriding is
the way to attain runtime polymorphism in Java. During the code execution, JVM decides
which implementation of the same method should be called.
➢ Dynamic Method Dispatch is another name for Runtime polymorphism.
➢ Here, the reference variable is referring to the object of class B. The reference variable
belongs to the superclass or parent class while the object is made up of the subclass or child
class. It is also known as upcasting.
➢ The subclasses exhibit an IS-A relationship with the parent class. For example, there can be
a class MobileOS. Since both Android as well as iOS are mobile operating systems, they are
the subclasses of MobileOS. So in terms of the IS-A relationship, we can say that
Android "IS A" MobileOS and iOS "IS A" MobileOS.
➢ The concept of upcasting can be seen in this example. Whether creating the object
of Android or iOS, the reference variable is of the superclass in both cases, i.e., MobileOS.

Example of Java Run Time Polymorphism


Example Java Program for Run time Polymorphism
//Creating a parent class
class MobileOS
{
//virtual method
void display()
{
System.out.println("We are talking about mobile operating systems.");
}
}
//Creating a child class for parent 'MobileOS'
class Android extends MobileOS
{

//overriding display method


void display()
{
System.out.println("Android is a MobileOS.");
}
}
//Creating a child class for parent 'MobileOS'
class iOS extends MobileOS
{
//overriding display method
void display()
{
System.out.println("iOS is a MobileOS.");
}
}
//Main class
class DemoMobileOS
{
//calling main method
public static void main (String[] args)
{
//Create an object of parent class
MobileOS os = new MobileOS();
os.display();
//Create an object of child class
os=new Android(); //Upcasting
os.display();
//Create an object of child class
os=new iOS(); //Upcasting
os.display();
}
}
Output: We are talking about mobile operating systems
Android is a MobileOS.
iOS is a MobileOS.

ABSTRACT CLASSES:
➢ A class that is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods. An abstract method is a method that is
declared without any implementation.

➢ Abstract class needs to be extended and its method implemented. It cannot be


instantiated.

➢ Abstract classes in Java implement the concept of Abstraction in Object Oriented


Programming.

➢ It can have final methods which will force the subclass not to change the body of the
method.

➢ It can have constructors and static methods also.


Abstract class: Syntax:

abstract class ClassName

// Abstract and Non-abstract methods

Abstract Method:

A method which is declared as abstract and does not have implementation is known as an
abstract method.

Syntax

abstract return_type method_name(parameters list);

Example Program:

abstract class Bike{

abstract void run();

class Honda4 extends Bike{

void run(){System.out.println("Running safely");

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

Output:

Running safely

Another Example Program:

abstract class Bank{

abstract int getRateOfInterest();

}
class SBI extends Bank{

int getRateOfInterest(){return 7;}

class PNB extends Bank{

int getRateOfInterest(){return 8;}

class TestBank{

public static void main(String args[]){

Bank b;

b=new SBI();

System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");

b=new PNB();

System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");

}}

Output:

Rate of Interest is 7%

Rate of Interest is 8%

Final with Inheritance

In Java, the final keyword is used to restrict the user. The java final keyword can be used in
many context.
➢ Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized. This is useful for declaring constants or other values that should not be
modified.
➢ Final methods: When a method is declared as final, it cannot be overridden by a subclass.
➢ Final classes: When a class is declared as final, it cannot be extended by a subclass.
Using final to Prevent Inheritance
When a class is declared as final then it cannot be subclassed i.e. no other class can extend it.
This is particularly useful, for example, when creating an immutable class like the
predefined String class. The following fragment illustrates the final keyword with a class:

Syntax:

final class A

// methods and fields

// The following class is illegal.

class B extends A

// ERROR! Can't subclass A

• Declaring a class as final implicitly declares all of its methods as final, too.
• It is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete implementations.

Using final to prevent overriding:

When a method is declared as final then it cannot be overridden by subclasses.


The Object class does this, a number of its methods are final. The following fragment illustrates
the final keyword with a method:

Syntax:

class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}

class B extends A
{
void m1()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}

Normally, Java resolves calls to methods dynamically, at run time. This is called late or dynamic
binding. However, since final methods cannot be overridden, a call to one can be resolved at
compile time. This is called early or static binding.

PACKAGES AND INTERFACES: PACKAGES

A Java package is a collection of similar types of sub-packages, interfaces, and classes. In


Java, there are two types of packages: built-in packages and user-defined packages.
The package keyword is used in Java to create Java packages.

Syntax to create package:

package package-name;

Where package is the keyword, package-name denotes name of the package

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: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

User-defined packages:
User-defined packages are those that developers create to incorporate different needs of
applications. In simple terms, User-defined packages are those that the users define.

Sub-package:

Packages that are defined inside another package is called subpackage. These are not
imported by default, they have to imported explicitly.

Example:

import java.util.*;

Here, util is a sub-package created inside java package.How to Access A Package?

Packages & Member Access

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1.Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.

2.Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class.

4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Importing Packages:
The import keyword is used to access all members of a package using the following statements

1. import package.*;
2. import package.classname;
3. fully qualified

1. Using packagename.*

The import keyword is used to make the classes and interface of another package accessible to the
current package.

Example of package that import the packagename.*

//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");}
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello

2. Using packagename.class name


//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
package mypack;
import pack.A;
class B
{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Using fully qualified name:

//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

OUTPUT:
Hello

INTERFACES:

An interface in Java is a blueprint of a class. It has static constants and abstract methods. The
interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

Declaration of an interface:

An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static and
final by default. A class that implements an interface must implement all the methods declared in the
interface.

Syntax:

interface interface_name

//declare constant fields

// declare methods that abstract by default

}
Example Program:

interface printable

Int MIN=5;

void print();

class A implements printable

public void print()

System.out.println(“The Min Constant Value is:”+MIN);

System.out.println("Hello");

public static void main(String args[]){

A6 obj = new A6();

obj.print();

OUTPUT:

The Min Constant Value is: 5

Hello
Multiple Inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

Example Program: Multiple Inheritance


interface Printable
{
void print();
}
interface Showable
{
void print();
}
class TestInterface implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface obj = new TestInterface();
obj.print();
}
}
Output:
Hello

Extending Interfaces in Java


A class implements an interface, but one interface extends another interface.

interface Printable
{
void print();
}

interface Showable extends Printable


{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}

Advantages of interfaces:
1) Interfaces can be used to enforce a contract- that is, provide a specification that classes must
implement certain methods if they want to use that interface

2) Interfaces are used to achieve multiple inheritance

3) Interfaces can be used to achieve loose coupling

You might also like