UNIT 2 Inheritance Packages Interfaces
UNIT 2 Inheritance Packages Interfaces
UNIT 2 Inheritance 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
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
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
➢ Provides flexibility to call the same method for different types of data.
➢ This reduces the execution time because the binding is done in compilation time itself.
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.
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:
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.
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
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.
➢ 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
➢ 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.
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:
➢ 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.
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.
//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:
//Parent class
class College
//Instance variable
int id=101;
void printDetails()
System.out.println("College ID:"+this.id);
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();
ob.printDetails();
Output:
Student Id:301
College ID:101
class College
College()
Student()
super();
Output:
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 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
@Override
}
@Override
@Override
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);
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.
➢ 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.
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.
➢ It can have final methods which will force the subclass not to change the body of the
method.
Abstract Method:
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Syntax
Example Program:
obj.run();
Output:
Running safely
}
class SBI extends Bank{
class TestBank{
Bank b;
b=new SBI();
b=new PNB();
}}
Output:
Rate of Interest is 7%
Rate of Interest is 8%
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
class B extends 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.
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.
package package-name;
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.*;
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.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
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.
//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
//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
}
Example Program:
interface printable
Int MIN=5;
void print();
System.out.println("Hello");
obj.print();
OUTPUT:
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.
interface Printable
{
void print();
}
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