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

CS270 Java 3 4

Uploaded by

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

CS270 Java 3 4

Uploaded by

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

UNIT-3

Use and Benefits of Inheritance in OOP

What is Inheritance?

Inheritance is a mechanism in which one class acquires the property of

another class. For example, a child inherits the traits of his/her parents. With

inheritance, we can reuse the fields and methods of the existing class. Hence,

inheritance facilitates Reusability and is an important concept of OOPs.

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 you to reuse the fields and methods of the existing class

when you create a new class. You can use the same fields and

methods already defined in the previous class.

Advantages of Inheritance

 Inheritance promotes reusability. ...

 Reusability enhanced reliability. ...

 As the existing code is reused, it leads to less development and

maintenance costs.

 Inheritance makes the sub classes follow a standard interface.

 Inheritance helps to reduce code redundancy and supports code

extensibility.
Types of Inheritance in Java

On the basis of class, there can be three types of inheritance in java: single,

multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through

interface only. We will learn about interfaces later.

When one class inherits multiple classes, it is known as multiple inheritance.

For Example:
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the

example given below, Dog class inherits the Animal class, so there is the

single inheritance.

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance.

As you can see in the example given below, BabyDog class inherits the Dog

class which again inherits the Animal class, so there is a multilevel

inheritance.

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical

inheritance. In the example given below, Dog and Cat classes inherits the

Animal class, so there is hierarchical inheritance.


Why multiple inheritance is not supported in java?

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 you inherit 2 classes. So whether you have same

method or different, there will be compile time error.

Inheriting Data members and Methods

Inheritance is the procedure in which one class inherits the attributes and

methods of another class. The class whose properties and methods are

inherited is known as the parent class or superclass. And the class that

inherits the properties from the parent class is the child class or derived class
Role of Constructors in inheritance

A constructor in Java is similar to a method with a few differences.

Constructor has the same name as the class name. A constructor doesn't have

a return type. A Java program will automatically create a constructor if it is

not already defined in the program. It is executed when an instance of the

class is created.

A constructor cannot be static, abstract, final or synchronized. It cannot be

overridden.

Java has two types of constructors:

1. Default constructor

2. Parameterized constructor
What is the order of execution of constructor in Java inheritance?

While implementing inheritance in a Java program, every class has its own

constructor. Therefore the execution of the constructors starts after the object

initialization. It follows a certain sequence according to the class hierarchy.

There can be different orders of execution depending on the type of

inheritance.

Constructors in Inheritance:

When a drived class is extended from the base class, the constructor of the

base class is executed first followed by the constructor of the derived class.

For the following Inheritance hierarchy , the constructors are executed in

the order:

1. C1- Parent

2. C2 - Child

3. C3 - Grandchild

Constructors during constructor overloading :

 When there are multiple constructors in the parent class, the

constructor without any parameters is called from the child class.


 If we want to call the constructor with parameters from the parent

class, we can use the super keyword.

 super(a, b) calls the constructor from the parent class which takes 2

variables

Source code as described in the video:

package com.company;

class Base1{

Base1(){

System.out.println("I am a constructor");

Base1(int x){

System.out.println("I am an overloaded constructor with

value of x as: " + x);

}}

class Derived1 extends Base1


Overriding Super Class Methods

In a class hierarchy, when a method in a subclass has the same name and

type signature as a method in its superclass, then the method in the subclass

is said to override the method in the superclass. When an overridden method

is called from within a subclass, it will always refer to the version of that

method defined by the subclass. The version of the method defined by the

superclass will be hidden.

A subclass may call an overridden superclass method by prefixing its name

with the super key word and a dot (.). Consider the following:
Use of “super”

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.

Polymorphism in inheritance
As the name implies, polymorphism is the ability to take multiple forms or

shapes. Polymorphism is an object-oriented programming concept that

allows you to treat objects that share the same superclass, whether directly or

indirectly, as though they were objects of the superclass. For example, we

inherit superclass methods in inheritance, while polymorphism uses the

methods in different forms.

Suppose we create a program that mimics the movement of animals.

Classes Dog, Fish, Bird, and Snake, for example, move differently even

though they all implement the move method in the superclass animal. The

code snippet below gives a vivid illustration to the statement above:

Public class Animal

public void animalMove() { System.out.println("Animal

move"); }}public class Dog extends Animal{ public void

animalMove() { System.out.println("Dog is

running"); }}public class Fish extends Animal{ public void

animalMove() { System.out.println("Fish is

swimming"); }}public class Bird extends Animal{ public void

animalMove() { System.out.println("Bird is flying"); }}public


class Snake extends Animal{ public void animalMove()

{ System.out.println("Snake is crawling"); }}

To test whether the above code applies polymorphism, let’s use the primary

method to test it.

public static void main(String[] args) { Animal animal = new Animal();

animal.animalMove(); Animal dog = new Dog(); dog.animalMove();

Animal fish = new Fish(); fish.animalMove(); Animal bird = new

Bird(); bird.animalMove(); Animal snake = new Snake();

snake.animalMove();}

The following will be printed out on our console when we run this

application:

Animal moveDog is runningFish is swimmingBird is flyingSnake is

crawling
Types of polymorphism

There are two types of polymorphism, and they are listed below:

1. Compile-time polymorphism

2. Run-time polymorphism

Compile-time polymorphism

When the compiler encounters a method call, it checks the object’s type to

determine if it can make that call. The program is compiled if the class

contains the method or inherits one. One primary application of

compile-time polymorphism is Java’s method overloading.

Method overloading

This is a concept in which methods are declared with the same name but

with different parameter types. The method is determined at compile time

hence the words compile-time in the name


Type conversion in Java with Examples

Java provides various data types just like any other dynamic languages

such as boolean, char, int, unsigned int, signed int, float, double, long, etc

in total providing 7 types where every datatype acquires different space

while storing in memory. When you assign a value of one data type to

another, the two types might not be compatible with each other. If the data

types are compatible, then Java will perform the conversion automatically

known as Automatic Type Conversion, and if not then they need to be cast

or converted explicitly. For example, assigning an int value to a long

variable.
Widening or Automatic Type Conversion

Widening conversion takes place when two data types are automatically

converted. This happens when:

 The two data types are compatible.

 When we assign a value of a smaller data type to a bigger data type.

Narrowing or Explicit Conversion


If we want to assign a value of a larger data type to a smaller data type we

perform explicit type casting or narrowing.

 This is useful for incompatible data types where automatic

conversion cannot be done.

 Here, the target type specifies the desired type to convert the

specified value to.

Type Promotion in Expressions

While evaluating expressions, the intermediate value may exceed the range

of operands and hence the expression value will be promoted. Some

conditions for type promotion are:

1. Java automatically promotes each byte, short, or char operand to int

when evaluating an expression.

2. If one operand is long, float or double the whole expression is

promoted to long, float, or double respectively.


Package

A java package is a group of similar types of classes, interfaces and

sub-packages. 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.

Here, we will have the detailed learning of creating and using user-defined

packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they

can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java

2. package mypack;

3. public class Simple{

4. public static void main(String args[]){


5. System.out.println("Welcome to package");

6. }

7. }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file.

You can use any directory name like /home (in case of Linux), 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. mypack.Simple etc to run the

class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destina

The . represents the current folder.

How to access package from another package?

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 subpackages.

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.*

1. //save by A.java

2. package pack;

3. public class A{

4. public void msg(){System.out.println("Hello");}

5. }

1. //save by B.java

2. package mypack;

3. import pack.*;

4.

5. class B{
6. public static void main(String args[]){

7. A obj = new A();

8. obj.msg();

9. }

10. }

Output:Hello

Accessing package without import keyword

If you use fully qualified name to import any class into your program, then

only that particular class of the package will be accessible in your program,

other classes in the same package will not be accessible. For this approach,

there is no need to use the import statement. But you will have to use the

fully qualified name every time you are accessing the class or the interface.

This is generally used when two packages have classes with same names.

For example: java.util and java.sql packages contain Date class.

Example
In this example, we are creating a class A in package pack and in another

class B, we are accessing it while creating object of class A.

//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();

} }
Hello

Import the Specific Class

Package can have many classes but sometimes we want to access only

specific class in our program in that case, Java allows us to specify class

name along with package name. If we use

import packagename.classname statement then only the class with name

classname in the package will be available for use.

Example:

In this example, we created a class Demo stored into pack package and in

another class Test, we are accessing Demo class by importing package name

with class name.

//save by Demo.java package pack; public class Demo {

public void msg() {

System.out.println("Hello");
} }

//save by Test.java package mypack; import pack.Demo; class Test {

public static void main(String args[]) {

Demo obj = new Demo();

obj.msg();

} }

Copy

Hello

Import all classes of the package

If we use packagename.* statement, then all the classes and interfaces of

this package will be accessible but the classes and interface inside

the sub-packages will not be available for use.

The import keyword is used to make the classes of another package

accessible to the current package.


Example :

In this example, we created a class First in learnjava package that access it

in another class Second by using import keyword.

//save by First.java package learnjava; public class First{

public void msg() {

System.out.println("Hello");

} }

//save by Second.java package Java; import learnjava.*; class

Second {

public static void main(String args[]) {

First obj = new First();

obj.msg();

} }
Hello

You might also like