Core Java Unit 3
Core Java Unit 3
BCA SEM - VI
Unit - 3
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:
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:
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”);
}
}
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.
}
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).
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.
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.
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.
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()
{
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.
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.
// overriding method
// with more accessibility
@Override
public void m2()
{
System.out.println("From child m2()");
}
}
// Driver class
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()
class Parent {
// Can't be overridden
final void show() {}
}
// 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()");
}
// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Child();
}
}
Output:
From parent static m1()
From child non-static(instance) m2()
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.
// 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 vs Overloading :
Overloading is about same method have different signatures. Overriding is about same
method, same signature but different classes connected through inheritance.
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.
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();
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()
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.
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()+" %");
}
}
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();
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
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
TOPIC – 7
Defining Package, Understanding of CLASSPATH.
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.
To Compile:
javac -d . FirstProgram.java
To Run:
java learnjava.FirstProgram
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
PATH CLASSPATH
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.
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
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
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
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)
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();
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();
}
}
Output:Hello
//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