Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Core Java Unit 3

The document discusses inheritance in Java, including: 1) It defines inheritance and describes how subclasses inherit properties from parent classes in Java. 2) It covers different types of inheritance in Java - single inheritance where a subclass inherits from one parent class, and multi-level inheritance where a subclass inherits from an intermediate parent class that already inherited from another parent class. 3) It provides examples of single inheritance with one subclass inheriting directly from one parent class, and multi-level inheritance with a subclass inheriting properties from a grandparent class through an intermediate parent class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Core Java Unit 3

The document discusses inheritance in Java, including: 1) It defines inheritance and describes how subclasses inherit properties from parent classes in Java. 2) It covers different types of inheritance in Java - single inheritance where a subclass inherits from one parent class, and multi-level inheritance where a subclass inherits from an intermediate parent class that already inherited from another parent class. 3) It provides examples of single inheritance with one subclass inheriting directly from one parent class, and multi-level inheritance with a subclass inheriting properties from a grandparent class through an intermediate parent class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Shree Adarsh BCA College - Hadadad

BCA SEM - VI

SUBJECT – 604 Core Java

Unit - 3

Unit – 3 INHERITANCE AND PACKEGES


TOPIC – 1 Inheritance Basic, Types of Inheritance
TOPIC – 2 Use of ‘super’ keyword.
TOPIC – 3 Method Overriding.
TOPIC – 4 Run Time Polymorphism: Dynamic Method Dispatch.
TOPIC – 5 Abstract Method and Class
TOPIC – 6 ‘final’ keyword with Inheritance.
TOPIC – 7 Defining Package, Understanding of CLASSPATH.
TOPIC – 8 Importing Package.
TOPIC – 9 Access Protection.

Prepared By :-BhaveshMehta
(bdmehta3300 @ gmail.com)

1
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

TOPIC -1
Inheritance Basic, Types of Inheritance

Inheritance Basic:

Inheritance is the concept of object oriented programming language.


Inheritance can be defined as the process where one class acquires the properties (methods
and fields(variables)) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
In other words we can say when one class gets the properties of another class it is called
inheritance.
Old class is known as base class or parent class or super class.
New class is known as derived class or subclass or child class.
Derived class inherits all or some of the properties from the base class.
How we can define derived class:-
Derived class can be defined by specifying its relationship with the base class in addition to its
own details.
Syntax to define derived class:-
class sub_class_name extends super_class_name
{
………….
…………. //Members of derived class
}
Keyword extends signifies that the properties of the super_class_name are inherited to the
sub_class_name.
Example:-
class ABC extends XYZ
{
members of ABC
}

REPARED BY: Bhavesh Mehta Page 2 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

Why do we need it?


Code Reusability: The code written in the Superclass is common to all subclasses. Child
classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is one of
the ways by which java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details is achieved
through inheritance. Abstraction only shows the functionality to the user.
Importance of Java inheritance
Implementation of inheritance in Java provides the following benefits:
Inheritance minimizes the complexity of a code by minimizing duplicate code. If the same
code has to be used by another class, it can simply be inherited from that class to its sub-
class. Hence, the code is better organized.
The efficiency of execution of a code increases as the code is organized in a simpler form.
The concept of polymorphism can be used along with inheritance.

Important Points
Code reuse is the most important benefit of inheritance because subclasses inherits the
variables and methods of superclass.
Private members of superclass are not directly accessible to subclass. As in this example,
Animal variable noOfLegs is not accessible to Cat class but it can be indirectly accessible via
getter and setter methods.
Superclass members with default access is accessible to subclass ONLY if they are in same
package.
Superclass constructors are not inherited by subclass.
If superclass doesn’t have default constructor, then subclass also needs to have an explicit
constructor defined. Else it will throw compile time exception. In the subclass constructor,
call to superclass constructor is mandatory in this case and it should be the first statement in
the subclass constructor.
Java doesn’t support multiple inheritance, a subclass can extends only one class. Animal
class is implicitly extending Object class and Cat is extending Animal class but due to java
inheritance transitive nature, Cat class also extends Object class.
We can create an instance of subclass and then assign it to superclass variable, this is
called upcasting. Below is a simple example of upcasting:

REPARED BY: Bhavesh Mehta Page 3 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

When an instance of Superclass is assigned to a Subclass variable, then it’s


called downcasting. We need to explicitly cast this to Subclass.

We can’t extend Final classes in java.


If you are not going to use Superclass in the code i.e your Superclass is just a base to keep
reusable code then you can keep them as Abstract class to avoid unnecessary instantiation by
client classes. It will also restrict the instance creation of base class.
We can’t extend Final classes in java.
If you are not going to use Superclass in the code i.e your Superclass is just a base to keep
reusable code then you can keep them as Abstract class to avoid unnecessary instantiation by
client classes. It will also restrict the instance creation of base class.

Types of Inheritance:-
Below are Various types of inheritance in Java. We will see each one of them one by one with
the help of examples and flow diagrams.

o Single Inheritance:-
o As the name suggests, this type of inheritance occurs for only a single class. Only one
class is derived from the parent class. In this type of inheritance, the properties are
derived from a single parent class and not more than that. As the properties are
derived from only a single base class the reusability of a code is facilitated along with
the addition of new features. The flow diagram of a single inheritance is shown below:
o Example:-

o Two classes Class A and Class B are shown in Figure 2, where Class B inherits the
properties of Class A.
o An example of a code applying single-level inheritance.
class A
{
public void method()
{
system.out.println(“Base class method”);
}
}

REPARED BY: Bhavesh Mehta Page 4 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

class B extends A
{
public void methodB()
{
system.out.println(“Child class method”):
}
public static void main(String args[])
{
B obj = new B();
obj.methodA();//calling super class method
obj.methodB();//calling local method
}
}

o Multi-level Inheritance
o The multi-level inheritance includes the involvement of at least two or more than two
classes. One class inherits the features from a parent class and the newly created sub-
class becomes the base class for another new class.
o As the name suggests, in the multi-level inheritance the involvement of multiple base
classes is there. In the multilevel inheritance in java, the inherited features are also
from the multiple base classes as the newly derived class from the parent class
becomes the base class for another newly derived class.

o An example of multi-level inheritance


Class X
{
Public void method();
{
System.out.println(“Class X method”);
}
}
Class Y extends X
{
Public void methodY()
{
System.out.println(“Class Y method”);
}

REPARED BY: Bhavesh Mehta Page 5 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

}
Class Z extends Y
{
Public void methodZ()
{
System.out.println(“Class Z method”);
}
Public static void main(String args[])
{
Z obj=new Z();
Obj.methodX();//calling grand parent class method
Obj.methodY();//calling parent class method
Obj.methodZ();//calling local method
}
}

o Hierarchical Inheritance
o The type of inheritance where many subclasses inherit from one single class is known
as Hierarchical Inheritance.
o Hierarchical Inheritance a combination of more than one type of inheritance.
o It is different from the multilevel inheritance, as the multiple classes are being derived
from one superclass. These newly derived classes inherit the features, methods, etc,
from this one superclass. This process facilitates the reusability of a code and dynamic
polymorphism (method overriding).

o An example of code showing the concept of 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()
{
REPARED BY: Bhavesh Mehta Page 6 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

System.out.println(“meowing……..”);
}
}
Class TestInheritance
{
Public static void main(String args[])
{
Cat c=new Cat();
c.eat();
c.meow();
}
}

o Multiple Inheritance
o Multiple inheritances is a type of inheritance where a subclass can inherit features
from more than one parent class. Multiple inheritances should not be confused
with multi-level inheritance, in multiple inheritances the newly derived class can have
more than one superclass. And this newly derived class can inherit the features from
these superclasses it has inherited from, so there are no restrictions. In java, multiple
inheritances can be achieved through interfaces.

o Hybrid Inheritance
o Hybrid inheritance is a combination of more than two types of inheritances single and
multiple. It can be achieved through interfaces only as multiple inheritance is not
supported by Java. It is basically the combination of simple, multiple, hierarchical
inheritances.

REPARED BY: Bhavesh Mehta Page 7 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

TOPIC – 2
Use of ‘super’ keyword.

Introduction:
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Use of Java super Keyword


The super keyword refers to superclass (parent) objects.
It is used to call superclass methods, and to access the superclass constructor.
The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
To understand the super keyword, you should have a basic understanding
of Inheritance and Polymorphism.
 super is used to refer immediate parent class instance variable.
o We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

Output:
black
white
o In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.

REPARED BY: Bhavesh Mehta Page 8 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

 super can be used to invoke parent class method


o The super keyword can also be used to invoke parent class method. It should be used
if subclass contains the same method as parent class. In other words, it is used if
method is overridden.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

Output:
eating...
barking...
o In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.
o To call the parent class method, we need to use super keyword.
 super is used to invoke parent class constructor.
o The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:
class Animal
{
Animal()
{

REPARED BY: Bhavesh Mehta Page 9 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

Output:
animal is created
dog is created
TOPIC – 3
Method Overriding

Introduction:

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In any object-oriented programming language, Overriding is a feature that allows a subclass
or child class to provide a specific implementation of a method that is already provided by
one of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature, and same return type(or sub-type) as a method in its super-
class, then the method in the subclass is said to override the method in the super-class.

REPARED BY: Bhavesh Mehta Page 10 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

Method overriding is one of the way by which java achieve Run Time Polymorphism.
The version of a method that is executed will be determined by the object that is used to
invoke it. If an object of a parent class is used to invoke the method, then the version in the
parent class will be executed, but if an object of the subclass is used to invoke the method,
then the version in the child class will be executed. In other words, it is the type of the object
being referred to (not the type of the reference variable) that determines which version of an
overridden method will be executed.

Usage of Java Method Overriding


Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
Method overriding is used for runtime polymorphism

Understanding the problem without method overriding


Let's understand the problem that we may face in the program if we don't use method
overriding.
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that
is why we use method overriding.

Understanding problem with method overriding


In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the
same, and there is IS-A relationship between the classes, so there is method overriding.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

REPARED BY: Bhavesh Mehta Page 11 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely

Rules for method overriding:


The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
Overriding and Access-Modifiers :
o The access modifier for an overriding method can allow more, but not less, access than
the overridden method. For example, a protected instance method in the super-class can
be made public, but not private, in the subclass. Doing so, will generate compile-time
error.
// A Simple Java program to demonstrateOverriding and Access-Modifiers
class Parent {
// private methods are not overridden
private void m1()
{
System.out.println("From parent m1()");
}

protected void m2()


{
System.out.println("From parent m2()");
}
}

class Child extends Parent {


// new m1() method
// unique to Child class
private void m1()
{
System.out.println("From child m1()");
}

// overriding method
// with more accessibility
@Override
public void m2()
{
System.out.println("From child m2()");
}
}

// Driver class

REPARED BY: Bhavesh Mehta Page 12 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Parent obj2 = new Child();
obj2.m2();
}
}
Output:
From parent m2()
From child m2()

Final methods can not be overridden :


o If we don’t want a method to be overridden, we declare it as final. Please see Using final
with Inheritance .
// A Java program to demonstrate that
// final methods cannot be overridden

class Parent {
// Can't be overridden
final void show() {}
}

class Child extends Parent {


// This would produce error
void show() {}
}
Output:
13: error: show() in Child cannot override show() in Parent
void show() { }
^
overridden method is final
Static methods can not be overridden(Method Overriding vs Method Hiding) :
o When you define a static method with same signature as a static method in base class, it is
known as method hiding.
o The following table summarizes what happens when you define a method with the same
signature as a method in a super-class.
Superclass Instance Method Superclass Static Method

Subclass Instance Generates a compile-time


Method Overrides error

Subclass Static Method Generates a compile-time error Hides

// Java program to show thatif the static method is redefined bya derived class, then it is
// not overriding, it is hiding
REPARED BY: Bhavesh Mehta Page 13 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

class Parent {
// Static method in base class
// which will be hidden in subclass
static void m1()
{
System.out.println("From parent "
+ "static m1()");
}

// Non-static method which will


// be overridden in derived class
void m2()
{
System.out.println("From parent "
+ "non-static(instance) m2()");
}
}

class Child extends Parent {


// This method hides m1() in Parent
static void m1()
{
System.out.println("From child static m1()");
}

// This method overrides m2() in Parent


@Override
public void m2()
{
System.out.println("From child "
+ "non-static(instance) m2()");
}
}

// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Child();

// As per overriding rules this


// should call to class Child static
// overridden method. Since static
// method can not be overridden, it
// calls Parent's m1()
obj1.m1();

// Here overriding works


// and Child's m2() is called
obj1.m2();

REPARED BY: Bhavesh Mehta Page 14 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

}
}
Output:
From parent static m1()
From child non-static(instance) m2()

Private methods can not be overridden :


o Private methods cannot be overridden as they are bonded during compile time. Therefore
we can’t even override private methods in a subclass.(See this for details).

The overriding method must have same return type (or subtype) :
o From Java 5.0 onwards it is possible to have different return type for an overriding
method in child class, but child’s return type should be sub-type of parent’s return type.
This phenomena is known as covariant return type.

Invoking overridden method from sub-class :


o We can call parent class method in overriding method using super keyword.
// A Java program to demonstrate that overridden method can be called from sub-class //
// Base Class
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}

// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show()
{
super.show();
System.out.println("Child's show()");
}
}

// Driver class
class Main {
public static void main(String[] args)
{
Parent obj = new Child();
obj.show();
}
}
Overriding and constructor :
o We can not override constructor as parent and child class can never have constructor
with same name(Constructor name must always be same as Class name).
REPARED BY: Bhavesh Mehta Page 15 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

Overriding and Exception-Handling :


o Below are two rules to note when overriding methods related to exception-handling.
o Rule-1 : If the super-class overridden method does not throw an exception, subclass
overriding method can only throws the unchecked exception, throwing checked
exception will lead to compile-time error.
o Rule-2 : If the super-class overridden method does throws an exception, subclass
overriding method can only throw same, subclass exception. Throwing parent
exception in Exception hierarchy will lead to compile time error.Also there is no issue
if subclass overridden method is not throwing any exception.
Overriding and abstract method:
o Abstract methods in an interface or abstract class are meant to be overridden in derived
concrete classes otherwise a compile-time error will be thrown.
Overriding and synchronized/strictfp method :
o The presence of synchronized/strictfp modifier with method have no effect on the rules of
overriding, i.e. it’s possible that a synchronized/strictfp method can override a non
synchronized/strictfp one and vice-versa.

Features of Method overloading


There are the following features of method overloading in java which you should have to
keep in mind.
o The call to overloaded method is bonded at compile time.
o The concept of method overloading is also known as compile-time polymorphism in java.
o Method overloading is generally done in the same class. But we can also do it in the
subclass. You need to make a relationship between the parent class and child class by
using extends keyword for it.
o Method overloading in Java cannot be done by changing the return type of the method
because there may occur ambiguity. But the overloaded methods can change the return
type.
o We can overload the private methods in Java.
o The final methods can be overloaded in Java.
o The main method can also be overloaded in Java.
o We can overload both static and instance methods in Java. Method overloading is possible
when two or more static methods with the same name, but the difference in the list of
parameters.

Overriding vs Overloading :
Overloading is about same method have different signatures. Overriding is about same
method, same signature but different classes connected through inheritance.

REPARED BY: Bhavesh Mehta Page 16 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

Overloading is an example of compiler-time polymorphism and overriding is an example


of run time polymorphism.

TOPIC – 4
Run Time Polymorphism: Dynamic Method Dispatch.

Introduction:
Dynamic method dispatch is the mechanism in which a call to an overridden method is
resolved at run time instead of compile time. This is an important concept because of how
Java implements run-time polymorphism.
Dynamic method dispatch is also known as run time polymorphism.
This technique is used to resolve a call to an overridden method at runtime rather than
compile time.
To properly understand Dynamic method dispatch in Java, it is important to understand the
concept of upcasting because dynamic method dispatch is based on upcasting.
o When an overridden method is called through a superclass reference, Java determines
which version(superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination is
made at run time.
o At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
o A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.

o Therefore, if a superclass contains a method that is overridden by a subclass, then when


different types of objects are referred to through a superclass reference variable, different
versions of the method are executed. Here is an example that illustrates dynamic method
dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
REPARED BY: Bhavesh Mehta Page 17 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = new C();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

REPARED BY: Bhavesh Mehta Page 18 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

// calling C's version of m1()


ref.m1();
}
}
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
Explanation :
o The above program creates one superclass called A and it’s two subclasses B and C. These
subclasses overrides m1( ) method.
o Inside the main() method in Dispatch class, initially objects of type A, B, and C are
declared.
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C

o Now a reference of type A, calledref, is also declared, initially it will point to null.
o A ref; // obtain a reference of tye A

o Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref,
one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of
m1( ) executed is determined by the type of object being referred to at the time of the
call.
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()

REPARED BY: Bhavesh Mehta Page 19 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

ref = b; // now r refers to a B object


ref.m1(); // calling B's version of m1()

ref = c; // now r refers to a C object


ref.m1(); // calling C's version of m1()

REPARED BY: Bhavesh Mehta Page 20 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

Why Method Overriding ?


As stated earlier, overridden methods allow Java to support run-time polymorphism.
Polymorphism is essential to object-oriented programming for one reason: it allows a general
class to specify methods that will be common to all of its derivatives while allowing
subclasses to define the specific implementation of some or all of those methods. Overridden
methods are another way that Java implements the “one interface, multiple methods” aspect
of polymorphism.

Advantages of dynamic method dispatch


It allows Java to support overriding of methods, which are important for run-time
polymorphism.
It allows a class to define methods that will be shared by all its derived classes, while also
allowing these sub-classes to define their specific implementation of a few or all of those
methods.
It allows subclasses to incorporate their own methods and define their implementation.

TOPIC – 5
Abstract Method and Class

Introduction:
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Abstract class in Java


An abstract class in Java is one that is declared with the abstract keyword.
It is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).
It can have abstract and non-abstract methods. It needs to be extended and its method
implemented.
Points to Remember
o In instance of an abstract class can not be created.
o Constructors are allowed.
o We can have an abstract class without any abstract method.
o There can be a final method in abstract class but any abstract method in class(abstract
class) can not be declared as final or in simpler terms final method can not be abstract
itself as it will yield an error: “Illegal combination of modifiers: abstract and final”
o We can define static methods in an abstract class
o We can use the abstract keyword for declaring top-level classes (Outer class) as well as
inner classes as abstract
o If a class contains at least one abstract method then compulsory should declare a class as
abstract
o If the Child class is unable to provide implementation to all abstract methods of
the Parent class then we should declare that Child class as abstract so that the next level
Child class should provide implementation to the remaining abstract method
REPARED BY: Bhavesh Mehta Page 21 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

Example of Abstract class in java


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

Abstract Method in Java


A method which is declared with abstract keyword and without a body (no
implementation) within an abstract class is known an abstract method.
The body is provided by the subclass (inherited from).
The abstract method will never be final because the abstract class must implement all the
abstract methods.
Rules of Abstract Method
o Abstract methods do not have an implementation; it only has method signature
o If a class is using an abstract method, they must be declared abstract. The opposite cannot
be true. This means that an abstract class does not necessarily have an abstract method.
o If a regular class extends an abstract class, then that class must implement all the abstract
methods of the abstract parent
Example of an abstract method
// Write a program To display method print the addition and subtraction by using
// abstraction.

abstract class arithmetic_operation


{
abstract void printInfo();
}
class add extends arithmetic_operation
{
void printInfo ()
{
REPARED BY: Bhavesh Mehta Page 22 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

int a = 3;
int b= 4;
System.out.println(a+b);

}
}
class sub extends arithmetic_operation
{
void printInfo()
{
int c=4;
int d=5;
System.out.println(c-d);
}
}
class abstraction
{
public static void main(String args[])
{
arithmetic_operation n = new add();
n.printInfo();
arithmetic_operation y = new sub();
y.printInfo();
}
}

Output
7
-1

TOPIC – 6
‘final’ keyword with Inheritance.

Introduction:

final is a keyword in java used for restricting some functionalities. We can declare variables,
methods, and classes with the final keyword.
During inheritance, we must declare methods with the final keyword for which we are
required to follow the same implementation throughout all the derived classes.
Note that it is not necessary to declare final methods in the initial stage of inheritance(base
class always). We can declare a final method in any subclass for which we want that if any
other class extends this subclass, then it must follow the same implementation of the method
as in that subclass.
The java final keyword can be used in context of inheritance. Final can be:
o variable
o method
o class
o Case 1: Declare final variable with inheritance
// Declaring Parent class
class Parent
REPARED BY: Bhavesh Mehta Page 23 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

{
/* Creation of final variable pa of string type i.e
the value of this variable is fixed throughout all
the derived classes or not overidden*/
final String pa = "Hello , We are in parent class variable";
}
// Declaring Child class by extending Parent class
class Child extends Parent
{
/* Creation of variable ch of string type i.e
the value of this variable is not fixed throughout all
the derived classes or overidden*/
String ch = "Hello , We are in child class variable";
}

class Test
{
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling a variable pa by parent object
System.out.println(p.pa);
// Creation of Child class object
Child c = new Child();

// Calling a variable ch by Child object


System.out.println(c.ch);
// Calling a variable pa by Child object
System.out.println(c.pa);
}
}

Output+
D:\Programs>javac Test.java
D:\Programs>java Test
Hello , We are in parent class variable
Hello , We are in child class variable
Hello , We are in parent class variable

o Case 2: Declare final methods with inheritance


// Declaring Parent class
class Parent
{
/* Creation of final method parent of void type i.e
the implementation of this method is fixed throughout
all the derived classes or not overidden*/
final void parent() {
System.out.println("Hello , we are in parent method");
}
}
REPARED BY: Bhavesh Mehta Page 24 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

// Declaring Child class by extending Parent class


class Child extends Parent
{

/* Creation of final method child of void type i.e


the implementation of this method is not fixed throughout
all the derived classes or not overidden*/
void child() {
System.out.println("Hello , we are in child method");
}
}

class Test
{
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling a method parent() by parent object
p.parent();
// Creation of Child class object
Child c = new Child();
// Calling a method child() by Child class object
c.child();
// Calling a method parent() by child object
c.parent();
}
}

Output
D:\Programs>javac Test.java
D:\Programs>java Test
Hello , we are in parent method
Hello , we are in child method
Hello , we are in parent method

o Case 3: Declare final class with inheritance


When a class is declared as final then it cannot be subclassed i.e. no other class can extend
it.
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// code
}
Output:
ERROR! Can't subclass A

REPARED BY: Bhavesh Mehta Page 25 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

TOPIC – 7
Defining Package, Understanding of CLASSPATH.

Introduction to Defining Package:

A java package is a group of similar types of classes, interfaces and sub-packages.


Think of it as a folder in a file directory. We use the packages to avoid naming conflicts and
to organize project-related classes, interfaces, and sub-packages into a bundle.
Packages are used for:
o 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
o Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
o 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.
o Packages can be considered as data encapsulation (or data-hiding).
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

How packages work?


Package names and directory structure are closely related. For example if a package name
is college.staff.cse, then there are three directories, college, staff and cse such that cse is
present in staff and staff is present college.
Also, the directory college is accessible through CLASSPATH variable, i.e., path of parent
directory of college is present in CLASSPATH. The idea is to make sure that classes are easy to
locate.
Package naming conventions : Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.
Define Package
Package program must be stored in directory, name of directory must be same as package
name.
REPARED BY: Bhavesh Mehta Page 26 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

To define package “Package” key word is used.


Class in package must as public.
All methods of class in package must also be defined as public.
Syntax for define package is,
package package_name;
Example,
package student;

Creating a package
Creating a package in java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.
package mypack;
public class employee
{
statement;
}
The above statement will create a package woth name mypack in the project directory.
Java uses file system directories to store packages. For example the .java file for any class you
define to be part of mypack package must be stored in a directory called mypack.

How to compile Java programs inside packages?


This is just like compiling a normal java program. If you are not using any IDE, you need to
follow the steps given below to successfully compile your packages:
javac -d directory javafilename
Example:
javac -d . FirstProgram.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like d:/abc (in case of windows) etc. If you want to keep the package within
the same directory, you can use . (dot).

How to run Java package program?


You need to use fully qualified name e.g. learnjava.FirstProgram etc to run the class.

To Compile:
javac -d . FirstProgram.java
To Run:
java learnjava.FirstProgram

Output: Welcome to package


Understanding of CLASSPATH:
CLASSPATH is actually an environment variable in Java.
CLASSPATH tells Java applications and the Java Virtual Machine (JVM) where to find the
libraries of classes.
An environment variable is a global system variable, accessible by the computer's operating
system (e.g., Windows). Other variables include COMPUTERNAME, USERNAME (computer's
name and user name).
In Java, CLASSPATH holds the list of Java class file directories, and the JAR file, which is Java's
delivered class library file.
If you're trying to run a stand-alone Java program, you may find it necessary to change the
CLASSPATH variable. When the program runs, Java's run-time system, called the interpreter,
REPARED BY: Bhavesh Mehta Page 27 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

is working through your code. If it comes across a class name, it will look at each directory
listed in the CLASSPATH variable. If it does not find the class name, it will error out.
We can set the value of CLASSPATH in DOS. The following example changes the variable to a
local folder that we've created called CustomClasses; it's located in a folder on the C: drive
called Java:

If you have your classes saved in a zip file, you can use the same command as above, except
add the name of the zip file:
c:\>set CLASSPATH = c:\Java\CustomClasses\classes.zip

Difference between PATH and CLASSPATH

PATH CLASSPATH

PATH is an environment variable. CLASSPATH is also an environment


variable.

It is used by the operating system to find It is used by Application ClassLoader to


the executable files (.exe). locate the .class file.

You are required to include the directory You are required to include all the
which contains .exe files. directories which contain .class and JAR
files.

PATH environment variable once set, The CLASSPATH environment variable can
cannot be overridden. be overridden by using the command line
option -cp or -CLASSPATH to both javac and
java command.

TOPIC – 8
Importing Package.

Importing Package:
In java, the import keyword used to import built-in and user-defined packages. When a
package has imported, we can refer to all the classes of that package using their name
directly.
The import statement must be after the package statement, and before any other statement.
Use import to access built-in and user-defined packages into your java source file so that your
class can refer to a class that is in another package by directly using its name.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

(1) Using packagename.*


 If you use package.* then all the classes and interfaces of this package will be
accessible but not sub packages.
REPARED BY: Bhavesh Mehta Page 28 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

 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.classname


 If you import package.classname then only declared class of this package will be
accessible.
 Example of package by import package.classname
//save by A.java

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

(3) Using fully qualified name


 If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.

REPARED BY: Bhavesh Mehta Page 29 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

 It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
 Example of package by import 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

TOPIC – 9
Access Protection.

Access Protection:
In java, the access modifiers define the accessibility of the class and its members. For
example, private members are accessible within the same class members only. Java has four
access modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the accessibility
of class members across the different packages.
In java we have four access protection:
1. Default
2. Private
3. Protected
4. Public

1. Default access protection

When we do not mention any access modifier, it is called default access protection.
The scope of this protection is limited to the package only.
This means that if we have a class with the default access protection in a package, only those
classes that are in this package can access this class.
No other class outside this package can access this class.
For example :

package abcpackage;
public class Addition
{
/* Since we didn't mention any access modifier here, it would
REPARED BY: Bhavesh Mehta Page 30 /33
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

* be considered as default.
*/
int addTwoNumbers(int a, int b)
{
return a+b;
}
}
Test.java
package xyzpackage;
/* We are importing the abcpackage
* but still we will get error because the
* class we are trying to use has default access
* modifier.
*/
import abcpackage.*;
public class Test
{
public static void main(String args[])
{
Addition obj = new Addition();
/* It will throw error because we are trying to access
* the default method in another package
*/
obj.addTwoNumbers(10, 21);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method addTwoNumbers(int, int) from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)

2. Private Access Protection:

The scope of private modifier is limited to the class only.


Private Data members and methods are only accessible within the class
Class and Interface cannot be declared as private
If a class has private constructor then you cannot create the object of that class from outside
of the class.
For example :
//Java program to illustrate error while sing class from different package with private modifier
package p1;
class A
{
private void display()
{
System.out.println("GeeksforGeeks");
}
}
//Java program to illustrate error while using class from different package with default
modifier

REPARED BY: Bhavesh Mehta Page 31 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

package p2;
import p1.*;
//This class is having default access modifier
class ExampleNew
{
public static void main(String args[])
{
//accessing class Example from package p1
Example obj = new Example();
obj.display();
}
}
Output:
error: display() has private access in A
obj.display();

3. Protected Access Protection:

Protected data member and method are only accessible by the classes of the same package
and the subclasses present in any package.
You can also say that the protected access protection is similar to default access protection
with one exception that it has visibility in sub classes.
Classes cannot be declared protected. This access protection is generally used in a parent
child relationship.
The protected access protection is accessible within package and outside the package but
through inheritance only.
The protected access protection can be applied on the data member, method and constructor.
It can't be applied on the class.
For example :
/save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}

REPARED BY: Bhavesh Mehta Page 32 /33


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM – VI 604-Core Java Unit –3

Output:Hello

4. Public Access Protection:


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
For example :

//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

REPARED BY: Bhavesh Mehta Page 33 /33

You might also like