[go: up one dir, main page]

0% found this document useful (0 votes)
28 views12 pages

Unit 2

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views12 pages

Unit 2

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

CORE COURSE – V: JAVA PROGRAMMING 23UCSCC43

UNIT -2
Inheritance: Basic concepts - Types of inheritance - Member access rules - Usage of this and Super key word -
Method Overloading - Method overriding - Abstract classes - Dynamic method dispatch - Usage of final keyword.
Packages: Definition - Access Protection - Importing Packages.
Interfaces: Definition – Implementation – Extending Interfaces.
Exception Handling: try – catch - throw - throws – finally – Built-in exceptions - Creating own Exception classes.

Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that we can create new classes that are built upon existing classes. When
we inherit from an existing class, we can reuse methods and fields of the parent class. Moreover, we can add new
methods and fields in your current class also.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o 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.
o 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.
o Reusability: As the name specifies, reusability is a mechanism which facilitates us to reuse the fields and
methods of the existing class when we create a new class. We can use the same fields and methods
already defined in the previous class.

General format for Inheritance


class superclass
{
// superclass data variables
// superclass member functions
}
class subclass extends superclass
{
// subclass data variables
// subclass member functions
}
Inheritance uses the “extends” keyword to create a derived class by reusing the base class code.

Extends keyword in JavaThe extended keyword extends a class and is an indicator that a class is being
inherited by another class. When we say class B extends a class A, it means that class B is inheriting the
properties(methods, attributes) from class A. Here, class A is the superclass or parent class and class B is the
subclass or child class.
Types of inheritance:

The different 5 types of Inheritance in java are:


Single inheritance.

 Multi-level inheritance.
 Multiple inheritance.
 Hierarchical Inheritance.
 Hybrid Inheritance.

Note: Multiple inheritance is not supported in Java through class.

Single Inheritance:

When a class inherits another class, it is known as a single inheritance. It means that the properties of the base
class are acquired by the derived class.

Example:
class A
{
int a, b;
void display()
{
System.out.println(“Inside class A values =”+a+” ”+b);
}
}
class B extends A
{
int c;

void show()
{
System.out.println(“Inside Class B values=”+a+” “+b+” “+c);
}
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B(); //derived class object
obj.a=10; Output:
obj.b=20; Inside class A values =10 20
obj.c=30; Inside Class B values=10 20 30
obj.display();
obj.show();
}
}
Note:
Even though a subclass includes all of the members of its super class, it cannot access those members who are
declared as Private in super class.

Super Keyword:

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

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

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


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(){
Output:
black whit
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();
}}
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.

2) super can be used to invoke parent class method


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

// Java code to show use of super keyword with variables


// Base class vehicle
class Vehicle {
int maxSpeed = 120;

void display() {
// print maxSpeed of base class (vehicle)
System.out.println("vehicle class display");
}
Output:
}
vehicle class display
// sub class Car extending vehicle
car class display
class Car extends Vehicle {
Maximum Speed: 120
int maxSpeed = 180;

void display() {
// print maxSpeed of base class (vehicle)
super.display();
System.out.println("car class display");
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args) {
Car small = new Car();
small.display();
}
}

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

class A
{
int a;
A(int a)
{
this.a=a;
System.out.println("a="+a);
}
}
class B extends A
{
int b;
B(int a,int b)
{
super(a);
System.out.println("b="+b);
}
}

class TestSuper
{
public static void main(String args[])
{
B obj=new B(4,5);
}
}
Output:
a=4
b=5

Multilevel Inheritance:

In simple inheritance a subclass or derived class derives the properties from its parent class, but in multilevel
inheritance a subclass is derived from a derived class. One class inherits only single class. Therefore, in
multilevel inheritance, every time ladder increases by one. The lower most class will have the properties of all
the super classes’
It is common that a class is derived from another derived class. The class student serves as a base class for the
derived class marks, which in turn serves as a base class for the derived class percentage. The class marks is
known as intermediates base class since it provides a link for the inheritance between student and percentage.
The chain is known as inheritance path. When this type of situation occurs, each subclass inherits all of the
features found in all of its super classes. In this case, percentage inherits all aspects of marks and student.

Example:

class student {
int rollno;

String name;

student(int r, String n)

{
rollno = r;
name = n;
}
void dispdatas() {
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
class marks extends student {
int total;

marks(int r, String n, int t) {


super(r, n); // call super class (student) constructor
total = t;
}
void dispdatam() {
dispdatas(); // call dispdatap of student class
System.out.println("Total = " + total);
}
}

class percentage extends marks {


int per;

percentage(int r, String n, int t, int p) {


super(r, n, t); // call super class(marks) constructor
per = p;
}
void dispdatap() {
dispdatam(); // call dispdatap of marks class
System.out.println("Percentage = " + per);
}
}
class Multi_Inhe {
public static void main(String args[]) {
percentage stu = new percentage(102689, "RATHEESH", 350, 70); // call constructor percentage
stu.dispdatap(); // call dispdatap of percentage class
}
} Output:
B class object
Output: method of Class A
Rollno = 102689 method of Class B
Name = RATHEESH C class object
Total = 350 method of Class A
Percentage = 70 method of Class C
D class object
Hierarchical Inheritance: method of Class A
method of Class D
In Hierarchical Inheritance, one class serves as a superclass (base A class object class) for
more than one sub class. In other words the process of deriving method of Class A multiple
subclasses from the same superclass is known as Hierarchical inheritance.
Example:

class A {
public void methodA() {
System.out.println("method of Class A");
}
}
class B extends A {
public void methodB() {
System.out.println("method of Class B");
}
}
class C extends A {
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A {
public void methodD() {
System.out.println("method of Class D");

}
}
class JavaExample {
public static void main(String args[]) {
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
System.out.println("B class object");
obj1.methodA();
obj1.methodB();
System.out.println("C class object");
obj2.methodA();
obj2.methodC();
System.out.println("D class object");
obj3.methodA();
obj3.methodD();
System.out.println("A class object");
A obj4 = new A();
obj4.methodA();
}
}
CDOE-ODL BSc(CS) – SEMESTER IV Unit II
Multiple Inheritance:
Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base
class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the dependency on two base
classes.

Note:
*To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
*Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be ambiguity to
call the method of A or B class.
*Since compile-time errors are better than runtime errors, Java renders compile-time error if we
inherit 2 classes. So whether we have same method or different, there will be compile time error.

Hybrid inheritance

A hybrid inheritance is a combination of more than one types of inheritance. For example when class
A and B extends class C & another class D extends class A then this is a hybrid inheritance, because it
is a combination of single and hierarchical inheritance.

MEMBER ACCESS RULES

25
CDOE-ODL BSc(CS) – SEMESTER IV Unit II
The modifiers are also known as access modifiers.
Java provides three types of visibility modifiers: public, private and protected.

Public Access:
To declare the variable or method as public, it is visible to the entire class in which it is
defined.
Example:
public int number;
public void sum ( ) {.......................}

Friendly Access:
When no access modifier is specified, the number defaults to a limited version of public
accessibility known as “friendly” level of access.

26
CDOE-ODL BSc(CS) – SEMESTER IV Unit II
The difference between the “public” and “friendly” access is that the public
modifier makes fields visible in all classes.
While friendly access makes fields visible only in the same package, but not in
other package.

Protected Access:
The protected modifier makes the fields visible not only to all classes
and subclasses in the same package but also to subclasses in other packages.
Non-subclasses in other packages cannot access the “protected” members.

Private Access:
Private fields are accessible only with their own class.
They cannot be inherited by subclasses and therefore not accessible in
subclasses. A method declared as private behaves like a method declared as
final.

Private protected Access:


A field can be declared with two keywords private and protected together like:

private protected int codeNumber;


This gives a visibility level in between the “protected” access and “private”
access. Use public if the field is to be visible everywhere.
Use protected if the field is to be visible everywhere in the current package and
also subclasses in other packages.
Use “default” if the field is to be visible everywhere in the current package only.

Access Control

Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access
modifiers.

27
CDOE-ODL BSc(CS)
The access modifiers in – SEMESTER
java specifies IV (scope) of a data member,
accessibility Unit II
method, constructor or class.

There are 4 types of java access modifiers:

28

You might also like