0% found this document useful (0 votes)
6 views

Java_Chapter _2

Chapter 2 discusses key concepts in Java such as inheritance, method overloading, method overriding, and the use of interfaces and packages. It explains types of inheritance, benefits, and rules for method overloading and overriding, along with the significance of the final and abstract keywords. Additionally, it covers the creation and implementation of user-defined packages for code reusability.

Uploaded by

anuprajput8605
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java_Chapter _2

Chapter 2 discusses key concepts in Java such as inheritance, method overloading, method overriding, and the use of interfaces and packages. It explains types of inheritance, benefits, and rules for method overloading and overriding, along with the significance of the final and abstract keywords. Additionally, it covers the creation and implementation of user-defined packages for code reusability.

Uploaded by

anuprajput8605
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 2.

Inheritance , Interface and Package

What is Inheritance?

Inheritance is a fundamental concept in object-oriented programming (OOP) where a


one class (called a subclass or derived class or child class ) is created based on an existing
class (called a superclass or base class or parent class).

Inheritance is the mechanism of deriving one class from already define class

The subclass inherits the properties (member variables and member method ) of
superclass.

Inheritance promotes code reusability, reduces redundancy of data in program.

Types of Inheritance in Java

Single Inheritance: A single class inherits from only one superclass is called as single
inheritance

Parent Class

Child Class

Syntax

class Parent
{
____
____
}
class Child extends Parent
{
____
____
}
For eg .

class Add1
{
int a=10,b=20,c;
void add()
{
c=a+b;
System.out.println("Addition="+c);
}
}
class SubData extends Add1
{
void sub()
{
System.out.println("Sub="+(b-a));
}
}
class Demo
{
public static void main(String args[])
{
SubData a1=new SubData();
a1.add();
a1.sub();
}
}

Multilevel Inheritance: A class inherits from a superclass, which in turn inherits from
another superclass, forming a hierarchy.

Parent Class

Child Class 1

Child Class 2
Syntax

class Parent
{
____
____
}
class Child1 extends Parent
{
____
____
}
class Child2 extends Child1
{
____
____
}
For Eg
class Grandfather
{
String s1 = "String of Grandfather";
}
class Father extends Grandfather
{
String s2 = "String of Father";
}
class Child extends Father
{
String s3= "String of Child";
void show()
{
System.out.println(“s1= “+s1+”s2 = ”+s2+”s3= “+s3);
}
}
class Demo
{
public static void main(String args[])
{
Child a1=new Child();
a1.show();
}
}
1. Hierarchical Inheritance: Multiple classes inherit from the same superclass is called
as hierarchical inheritance

Important Notes

• Java does not support multiple inheritance (a class inheriting from multiple classes)
through classes. This is to avoid the "diamond problem" (ambiguity in inherited
members).

• Multiple inheritance can be achieved using interfaces in Java.

Benefits of Inheritance

• Code Reusability: Common code can be placed in the superclass and reused by
subclasses.

• Reduced Redundancy(Reduced Duplicate data ): Avoids writing the same code


multiple times.

Method overloading
Method overloading in Java is a powerful feature that allows programmer to define multiple
methods within the same class that have the same name but different parameters. The
compiler distinguishes between these methods based on the number, types, or order of
their parameters.

Why Use Method Overloading?

• Flexibility: It provides flexibility in how you call a method, allowing you to pass
different types or numbers of arguments.

Rules for Method Overloading

1. Same Method Name: The methods must have the same name.
2. Different Parameter Lists: The methods must differ in at least one of the following:

o Number of parameters: A method with two parameters can be overloaded


with a method that has three parameters i.e method with same name have
different number of parameters.

o Types of parameters: A method must have different parameters .

o Order of parameters: A method that takes an int and then a float is different
from a method that takes a float and then an int.

3. Return Type is Not a Factor: The return type of the method does not play a role in
method overloading so it doesn’t matter what type of value is method returning.
Two methods can have the same name, different parameter lists and different return
types or same return type, and this is perfectly valid overloading.

Example

class Calculator
{
// Method 1: Adds two integers
int add(int a, int b)
{
System.out.println(“Addition =” +( a + b)); //a=2,b=3 so (2+3=5)
}
// Method 2: Adds three integers
int add(int a, int b, int c)
{
System.out.println(“Addition =” +( a+b+c)); //a=2,b=3 ,c=4 so
(2+3+4=9)

}
public static void main(String args[])
{
Calculator calc = new Calculator();

calc.add(2, 3); // Calls Method 1 (int, int) Output: 5


calc.add(2, 3, 4); // Calls Method 2 (int, int, int) Output: 9
}
}
Explanation

• The Calculator class has two methods, all named add().

• The compiler determines which add method to call based on the arguments you
provide in the main method.

• calc.add(2, 3) calls the first add method because it matches the signature (int, int).

• calc.add(2, 3, 4) calls the second add method because it matches (int, int, int).

Important Note: If you try to call an overloaded method and the compiler cannot find
a unique match, you will get a compile-time error. This is called "ambiguous method call."

Method Overriding
Method overriding in Java allows a subclass (child class) to provide a specific implementation
for a method that is already defined in its superclass (parent class). This lets the subclass
customize the behavior of the inherited method to suit its own needs.

Method overriding is essential for achieving polymorphism (the ability of an object to take
on many forms with same name)

Subclasses need to perform method that are similar to their superclass method but with
some modifications. Overriding keep the same method name and same parameter list (for
consistency) but change the implementation(different body).

Rules for Method Overriding

1. Same Method Signature: The overriding method in the subclass must have the same
name, same parameter list (number and types of parameters) as the method in the
superclass. The method signature must be identical(same).

2. Access Modifier: The access modifier of the overriding method in the


subclass cannot be more restrictive than the access modifier of the overridden
method in the superclass. For example:

o If the superclass method is public, the subclass method must also be public.

o If the superclass method is protected, the subclass method can


be protected or public.

o You cannot override a public method with a protected or default (package-


private) method.
Example

class Flower

void color()

System.out.println("Pink");

class Rose extends Flower

void color()

System.out.println("Red");

class MainDemo

public static void main(String args[])

Flower r=new Flower();

r.color() // Output:Pink

Rose s=new Rose();

s.color() // Output:Red

Overriding is about providing a different implementation for an existing method inherited


from a superclass.
Use of super keyword
The subclass can access all the members of super class except private data members ,when
the superclass is created which want to keep its implementation details to itself only . In
such cases, the subclass cannot access these members directly as per the encapsulation
(OOP Concept). The Java provides solution to this problem, whenever a subclass needs to
refer to its immediate superclass with keyword super.

The super keyword is used to invoke the super class constructor from subclass constructor. It
is used if super class has a parameterized constructor. It can be used only from the subclass
constructor and it has to be the first instruction in the subclass constructor.

The super has two general forms:

i. First that calls the superclass' constructor


ii. Second is used to access a member of the superclass that has been hidden by the member
of a subclass.

Accessing Superclass Members: The super is same as this except that it always refers to the
superclass of the subclass in which it is used. It has following format

super.member

for eg.
class Flower
{
void color()
{
System.out.println("Pink");
}
}
class Rose extends Flower
{
void color()
{
super.color();
System.out.println("Red");
}
}
class MainDemo
{
public static void main(String args[])
{
Rose s=new Rose();
s.color() // Output:Red
}
}

final
In Java, the final keyword is a powerful modifier that can be applied to variables, methods,
and classes. It has different meanings and effects depending on where it's used for eg-final
variable , final method or final class

1. final Variable

A final variable's value cannot be changed after it has been initialized. It's essentially a
constant i.e final variable store fixed value .

Declaration :

final int MAX_VALUE = 100; // Initialization at declaration

You must initialize a final variable. You can do it at the time of declaration only once.

final variables are often used for constants (values that should not change throughout
the program). By convention, constant names are often written in uppercase with
underscores (e.g., MAX_VALUE, PI).

2. final Method

A final method cannot be overridden by subclasses. This prevents subclasses from


changing the implementation of the method.

How to Declare:

class Parent

final void myMethod()

// ... implementation ...

final methods are used when you want to ensure that the behavior of a method remains
consistent and is not modified by subclasses.
3. final Class

A final class cannot be subclassed (inherited from). This prevents other classes from
extending the final class.

How to Declare:

final class MyClass

// ... class members ...

// This will cause a compile-time error:

// class AnotherClass extends MyClass

final classes are used when you want to create a class that is immutable (its state cannot be
changed after creation) or when you want to prevent others from creating subclasses that is
preventing inheritance.

All methods in a final class are implicitly final (you don't need to explicitly declare them
as final).

Abstract Method
An abstract method is a method that is declared without an implementation (no method
body). It essentially acts as a placeholder specifying that subclasses(child class) must provide
a concrete implementation for that method.

How to Declare:

abstract void myMethod(); // No curly braces or method body

Note:

o Abstract methods can only exist within abstract classes (explained below).

o They are declared using the abstract keyword.

o They do not have a body (no curly braces {}). The declaration ends with a
semicolon.
o Subclasses that inherit from the abstract class must override all the abstract
methods and provide concrete implementations. If a subclass doesn't provide
an implementation, it must also be declared as abstract.

Abstract Class
An abstract class is a class that cannot be instantiated directly(We can not create object for
abstract class). It can contain both abstract methods (which must be implemented by
subclasses) and concrete methods (which have body).

• How to Declare:

abstract class MyAbstractClass

// ... members (fields and methods) ...

• Note:

o Abstract classes are declared using the abstract keyword.

o You cannot create objects of an abstract class directly. For


example, MyAbstractClass obj = new MyAbstractClass(); would be a compile-
time error.

o Abstract classes can have both abstract methods and concrete (non-abstract)
methods.

o If a class has even one abstract method, the class itself must be declared as
abstract.

o Subclasses of an abstract class must implement all the abstract methods of


the superclass, or they must themselves be declared as abstract.

Interface
Interface is also known as kind of class so it also contain methods and variables but with
major difference of only abstract method and final variable i.e method do not specify any
code and the data variables are constant hence it is the child class responsibility to
implement code for abstract method.

Syntax for defining interface is:


interface InterfaceName
{
return_type method_namel (Parameter list);
return_type method_name2(Parameter list);
type final-variable 1 = valuel;
type final-variable 2 = value2;
}
Variables of interface are declared final (as constants), meaning that the implementing class
cannot change them.

Method declaration contains only list of methods without any body statement and ends with
semicolon. The methods are, essentially, abstract methods; there can be no default
implementation of any method specified within an interface. Each class that includes an
interface must implement all of the methods.

Following example is of interface definition, which contains two variables and one method.

interface student

final int rollno = 11;

final String name = "Ram";

abstract void display();

The code for implementation of the method is not provided in the interface. The method
declaration terminated with semicolon. Now this is the responsibility of the class that
implements this interface to define the code for the method.

Extending Interfaces
Interface can be extended like classes. That is, an interface can be subinterfaced from other
interfaces. The newly subinterface can inherit all the members of superinterface is the
manner like subclasses. The extend keyword is used. The syntax is:

interface Name

Body of Name1 interface

interface SubName2 extends Name

{
body of SubName2;

Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.
Interfaces are used as "superclass" whose properties are inherited by classes. So create a
class that inherits the interface. To implement an interface, include the implements clause in
a class definition and then override the methods defined by the interface.

The syntax is:

class ClassName extends Superclass implements interface

body of ClassName;

Here,

(i) A class can extend another class while implementing interfaces

(ii) Class_Name "implements" interface interfaceName.

(iii) If a class implements more than one interface, then interfaces must be separated with
commas.

General form of implementation is

class ClassName extends Superclass implements interface1, interface2

body of ClassName;

For eg

interface Area

{ // interface defined

float pi = 3.14F;

float compute(float x, float y); // ABSTRACT METHOD

class Rectangle implements Area


{ // interface is implemented

public float compute(float x, float y) {

return (x * y);

class Demo

public static void main(String args[])

Rectangle r1=new Rectangle();

System.out.println(r1.compute(1.2f,3.2f));

Package
Reusability can be achieved through inheritance and interfaces by extending the classes and
implementing the interfaces. But this is limited to reusing the classes within a program.

Suppose, if we want to use the classes from other programs without actually copying them
into program then this can be achieved in Java by using packages which is very similar to
class libraries in other libraries. Another way of achieving the reusability concept in Java is
packages.

Packages are used for grouping a variety of classes and interfaces together. This grouping is
done according to the functionality. Packages are acts as "containers" for classes that are
used to keep the class name space compartmentalized. Packages are stored in hierarchical
manner and are explicitly imported into new class definitions.

Creating User Define Package

package pack; //Creating Package

public class AddNum //make class public to access everywhere

public int add(int a,int b) //make method public to access everywhere


{
return a+b;

}
}

Steps to Save File-

1. create subdirectory with name pack

2. Save file with AddNum.java in pack directory.

(write below code in new file)

import java.util.*; //import package for scanner class access

import pack.AddNum; //import our own created package


class AddData

public static void main(String args[]) //main method

Scanner sc=new Scanner(System.in);

System.out.println("Enter number1");

int num1=sc.nextInt();
System.out.println("Enter number2");

int num2=sc.nextInt();

AddNum an= new AddNum(); //creating object of public class in user


define package

int result= an.add(num1,num2); //calling method from package

System.out.println("Addition = "+result);

Steps to save file

1 save file with AddData.java name in same directory of pack


Steps to run program

1. open cmd on location of pack directory


2. compile public class in package creation file as
javac -d . AddNum.java

3. compile java source code for executing main method as follows


javac -d . AddData.java

4.Now run program simply

java AddDemo

You might also like