0% found this document useful (0 votes)
3 views38 pages

Unit 3

The document outlines the syllabus for Unit-3 of the Java programming course for BCA NEP, focusing on inheritance and polymorphism. It covers key concepts such as types of inheritance, method overriding, the super keyword, polymorphism types, generics, type casting, and the instanceof operator. Additionally, it explains the use of abstract classes and interfaces for data abstraction in Java.
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)
3 views38 pages

Unit 3

The document outlines the syllabus for Unit-3 of the Java programming course for BCA NEP, focusing on inheritance and polymorphism. It covers key concepts such as types of inheritance, method overriding, the super keyword, polymorphism types, generics, type casting, and the instanceof operator. Additionally, it explains the use of abstract classes and interfaces for data abstraction in Java.
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/ 38

Java not unit 3 ll sem Bca NEP Syllables

Java programming (Bengaluru North University)

Scan to open on Studocu

Downloaded by Thirumala Sarawad


Studocu is not sponsored or endorsed by any college or university

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Unit-3: Inheritance and Polymorphism

Inheritance in java, Super and sub class, Overriding, Object class,


Polymorphism, Dynamic binding, Generic programming, Casting
objects, Instance of operator, Abstract class, Interface in java,
Package in java, UTIL package.

------------------------------------------------------------------------------------------------

Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviors of a parent object.

In Inheritance, the properties of the base class are acquired by the derived
classes.

extends is the keyword used to inherit the properties of a class.

Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Page 1

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Example Program

class Base
{
public void M1()
{
System.out.println(“ Base Class Method ”);
}
}
class Derived extends Base
{
public void M2()
{
System.out.printIn(“ Derived Class Methods “);
}
}
class Test
{
public static void main(String[] args)
{
Derived d = new Derived(); // creating

object d.M1(); // print Base Class Method

d.M2(); // print Derived Class Method


}
}

The main advantage of inheritance is code reusability and also method


overriding (runtime polymorphism).

Inheritance is also known as the IS-A relationship.

Page 2

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Types of Inheritance

The different 6 types of Inheritance in java are:

 Single inheritance.
 Multi-level inheritance.
 Hierarchical Inheritance.
 Multiple inheritance.
 Hybrid Inheritance.
Note: In java programming, multiple and hybrid inheritance is supported
through interface only.

1) Single inheritance.

Creating subclasses from a single base class is called single inheritance.

Class B inherits the properties of Class A.

Example program

class Animal
{

void eat()
{
System.out.println("eating...");}
}

Page 3

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

class Dog extends Animal


{
void bark()
{
System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new
Dog(); d.bark();
d.eat();
}
}
Output:

barking...
eating...

2) Multi-level inheritance.
When there is a chain of inheritance, it is known as multilevel inheritance.

Class B is a derived class from Class A, and Class C is further derived from
Class B.

Page 4

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Example

Program class

Animal

void eat()
{
System.out.println("eating...");
}
}

class Dog extends Animal


{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}

Page 5

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

}
Outpu
t:
weeping
...
barking..
.
eating...

3) Hierarchical Inheritance.
In Hierarchical Inheritance in Java, more than one derived class extends a
single base class.

Class B, Class C, and Class D are inherited from the single Class A. All the
child classes have the same parent class in hierarchical inheritance.
Example: An example of code showing the concept of hierarchical inheritance

Example

Program class

Animal
{
void eat()
{
System.out.println("eating...");
}
}

Page 6

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

class Dog extends Animal{


void bark()
{
System.out.println("barking...");
}
}

class Cat extends Animal{


void meow()
{
System.out.println("meowing...");}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new
Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:

meowing...
eating...

Page 7

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Multiple Inheritance

Defining derived class from numerous base classes is known as


‘Multiple Inheritance

Multiple inheritances is not supported in java. But it can be achieved


through interfaces
Hybrid Inheritance
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.

Page 8

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Method overriding
In Java, method overriding occurs when a subclass (child class) has the same
method as the parent class.

Example program

Output:

I am a dog.

In the above program, the displayInfo() method is present in both the


Animal superclass and the Dog subclass.

When we call displayInfo() using the d1 object (object of the subclass),


the method inside the subclass Dog is called. The displayInfo() method of the
subclass overrides the same method of the superclass.

Page 9

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Java Overriding Rules

 Both the superclass and the subclass must have the same
method name, the same return type and the same parameter
list.
 We cannot override the method declared as final and static.

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer


immediate parent class object.

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.

super to call 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.

Page 10

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

super to invoke immediate 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.

Page 11

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

super is used to invoke parent class constructor.

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

Page 12

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Object class

Object class is present in java.lang package. The Object class is the


parent class of all the classes in java by default. In other words, it is the
topmost class of java.

Page 13

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Page 14

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Polymorphism in java

polymorphism is a concept of object-oriented programming that allows us


to perform a single action in different forms

The word polymorphism is a combination of two words i.e. ploy and


morphs. The word poly means many and morphs means different forms.
In short, a mechanism by which we can perform a single action in different
ways.

Types of Polymorphism

There are two types of polymorphism in Java:

o Static Polymorphism (Compile Time Polymorphism)


o Dynamic Polymorphism (Run Time Polymorphism)

Page 15

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Static polymorphisum

This polymorphism is resolved during the compiler time and is


achieved through the method overloading. (Compile-time
Polymorphism) Static Polymorphism in Java decides which method to
execute during compile time.

class Shapes
{
public void area()
{
System.out.println("Find area ");
}
public void area(int r)
{
System.out.println("Circle area = "+3.14*r*r);
}

public void area(double b, double h)


{
System.out.println("Triangle area="+0.5*b*h);
}
public void area(int l, int b)
{
System.out.println("Rectangle area="+l*b);

Page 16

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

class Main {
public static void main(String[] args)
{
Shapes myShape = new Shapes(); // Create a Shapes object

myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);

}
}
Output:

Find area
Circle area =
78.5 Triangle
area=3.60
Rectangle
area=12

Dynamic Polymorphism

Dynamic polymorphism is a process or mechanism in which a call to an


overridden method is to resolve at runtime rather than compile-time. It is
also known as runtime polymorphism or dynamic method dispatch. We
can achieve dynamic polymorphism by using the method overriding.

Page 17

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

The Java Generics allows us to create a single class, interface, and method
that can be used with different types of data (objects).

Page 18

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Java Generics Class

 A single class that can be used with any type of data is known as
Generics Class.
 Generic class declaration looks like a non-generic class declaration,
except that the class name is followed by a type parameter section.
class Demo<T>
{
Ta;
void getdata(T x)
{
this.a=x;
}
T dispaly()
{
return a;
}
}

class G1
{
public static void main(String args[])
{
Demo <Integer> d=new
Demo(); Demo <String>
s=new Demo();
d.getdata(new Integer(10));
s.getdata(new
String("hello"));
System.out.println(d.dispaly()
);
System.out.println(s.dispaly()
);
}
}
output

Page 19

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Generics Method

Generic method is a single method declaration, that can be used with any
type of data. Such a method is known as Generics Method.

..

Page 20

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Advantage of generics in java

 Generics ensure compile-time safety which allows the programmer to


catch the invalid types while compiling the code.
 Java Generics helps the programmer to reuse the code for whatever
type he/she wishes. For instance, a programmer writes a generic
method for sorting an array of objects. Generics allow the programmer
to use the same method for Integer arrays, Double arrays, and even
String arrays.
 Another advantage of using generics is that Individual typecasting isn’t
required. The programmer defines the initial type and then lets the
code do its job.
 It allows us to implement non-generic algorithms.

Page 21

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

TYPE CASTING

Type casting is a way of converting data from one data type to another data
type.

Java will perform the conversion automatically known as Automatic Type


Conversion and if not, then they need to be casted or converted explicitly.

There are two major types of casting in Java as follows:

 Widening Casting (automatically) – This involves the conversion


of a smaller data type to the larger type size.

byte -> short -> char -> int -> long -> float -> double

Example program

class Main {

public static void main(String[] args) {

// create int type

variable int num = 10;

System.out.println("The integer value: " + num);

// convert into double type

double data = num;

System.out.println("The double value: " + data);

}}

Output

The integer value:

10 The double value:

10.0

Page 22

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

In the case of Widening Type Casting, the lower data type (having
smaller size) is converted into the higher data type (having larger
size). Hence there is no loss in data.

 Narrowing Casting (manually) – This involves converting a larger


data type to a smaller size type.

double -> float -> long -> int -> char -> short ->

byte class Main {

public static void main(String[] args) {

// create double type

variable double num =

10.99;

System.out.println("The double value: " + num);

// convert into int

type int data =

(int)num;

}System.out.println("The integer value: " + data);

Outpu
t

The double value:

10.99 The integer

value: 10

In the case of Narrowing Type Casting, the higher data types


(having larger size) are converted into lower data types (having
smaller size). Hence there is the loss of data. This is why this type of
conversion does not happen automatically.

Page 23

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Instanceof operator in Java

The instanceof operator in Java is used to check whether an object is an


instance of a particular class or not.

Syntax

objectName instanceOf className;

Here, if objectName is an instance of className, the operator returns true.


Otherwise, it returns false.

Example Program

class Main {

public static void main(String[] args)

// create a variable of string

type String name =

"Programiz";

// checks if name is instance of String

boolean result1 = name instanceof

String;

System.out.println("name is an instance of String: " + result1);

// create an object of

Main Main obj = new

Main();

// checks if obj is an instance of Main

boolean result2 = obj instanceof

Main;

System.out.println("obj is an instance of Main: " + result2);

Page 24
Downloaded by Thirumala Sarawad
Course II_BCA NEP Syllabus

Output

name is an instance of String:

true obj is an instance of Main:

true

Abstract classes and interfaces.

Data abstraction is the process of hiding certain details and showing only
essential information to the
user. Abstraction can be achieved with either
abstract classes or interfaces

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface

(100%) Abstract

class in Java

A class which is declared as abstract is known as an abstract class. It can


have abstract and non-abstract methods.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.

Example Program1

abstract class Bike


{
abstract void run();
}

Page 25

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

class Honda extends Bike


{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Honda obj = new
Honda(); obj.run();
}
}
Example program2

abstract class
Animal {
abstract void

makeSound(); public

void eat()
{
System.out.println("I can eat.");
}
}

Page 26

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

class Dog extends Animal


{

// provide implementation of abstract


method public void makeSound()
{
System.out.println("Bark bark");
}
}

class Main
{
public static void main(String[] args)
{
// create an object of Dog
class Dog d1 = new Dog();
d1.makeSound();
d1.eat();
}
}
Output

Bark
bark I
can eat.

Interfaces
Another way to achieve abstraction in Java, is with interfaces.

An interface in Java is a blueprint of a class. It has static constants and


abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be


only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.

Page 27

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Syntax

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Example Program

interface Polygon

void getArea(int length, int breadth);

// implement the Polygon

interface class Rectangle

implements Polygon

{
Page 28

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

// implementation of abstract method

public void getArea(int length, int

breadth) {

System.out.println("The area of the rectangle is " + (length * breadth));

class Main {

public static void main(String[]

args) { Rectangle r1 = new

Rectangle(); r1.getArea(5, 6);

Output

The area of the rectangle is 3

Implementing Multiple Interfaces

In Java, a class can also implement multiple interfaces. For


example, interface A
{
// members of A
}

interface B
{
// members of B
}

Page 29

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

class C implements A, B
{
// abstract members of A
// abstract members of B
}

PACKAGE IN JAVA

Package in Java is a mechanism to encapsulate a group of classes, sub


packages and interfaces.
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.

Page 30

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Built-in Package

Built-in packages are existing java packages that come along with the JDK. For
example, java.lang, java.util, java.io,

To use a class or a package from the library, you need to use the import
keyword:

Syntax

import package.name.Class; // Import a single

class import package.name.*; // Import the whole

package

Page 31

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Example
import
java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.

User-defined Package
Java also allows you to create packages as per your need. These
packages are called user-defined packages.
To define a package in Java, you use the keyword

package. package packageName;

Example Program

package p1;

public class

A
{
public void display()
{
System.out.println("display of A class");
}
}

 javac –d . A.java

 Now lets see how to use this package in another


program. import p1.*;
public class Demo
{
Page 32

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

public static void main(String args[])


{
A aa=new
A();
aa.display();
}
}
 Javac Demo.java
 Java Demo

JAVA.UTIL PACKAGE

It contains the collections framework, legacy collection classes, event model,


date and time facilities, internationalization, and miscellaneous utility classes
(a string tokenizer, a random-number generator, and a bit array).

1. AbstractCollection: This class provides a skeletal implementation of


the Collection interface, to minimize the effort required to implement
this interface.
2. AbstractList: This class provides a skeletal implementation of the List
interface to minimize the effort required to implement this interface
backed by a “random access” data store (such as an array).
3. AbstractMap<K,V>: This class provides a skeletal implementation of
the Map interface, to minimize the effort required to implement this
interface.
4. AbstractMap.SimpleEntry<K,V>: An Entry maintaining a key and a
value.
5. AbstractMap.SimpleImmutableEntry<K,V>: An Entry maintaining
an immutable key and value.
6. AbstractQueue: This class provides skeletal implementations of some
Queue operations.
7. AbstractSequentialList: This class provides a skeletal implementation
of the List interface to minimize the effort required to implement this
interface backed by a “sequential access” data store (such as a linked
list).
8. AbstractSet: This class provides a skeletal implementation of the Set
interface to minimize the effort required to implement this interface.
9. ArrayDeque: Resizable-array implementation of the Deque interface.
10. ArrayList: Resizable-array implementation of the List interface.
11. Arrays: This class contains various methods for manipulating
arrays (such as sorting and searching).
12. BitSet: This class implements a vector of bits that grows as needed.

Page 33

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

13. Calendar: The Calendar class is an abstract class that provides


methods for converting between a specific instant in time and a set of
calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so
on, and for manipulating the calendar fields, such as getting the date of
the next week.
14. Collections: This class consists exclusively of static methods that
operate on or return collections.
15. Currency: Represents a currency.
16. Date: The class Date represents a specific instant in time,
with millisecond precision.
17. Dictionary<K,V>: The Dictionary class is the abstract parent of
any class, such as Hashtable, which maps keys to values.
18. EnumMap,V>: A specialized Map implementation for use with enum
type keys.
19. EnumSet: A specialized Set implementation for use with enum types.
20. EventListenerProxy: An abstract wrapper class for an
EventListener class which associates a set of additional parameters
with the listener.
21. EventObject: The root class from which all event state objects shall
be derived.
22. FormattableFlags: FomattableFlags are passed to the
Formattable.formatTo() method and modify the output format for
Formattables.
23. Formatter: An interpreter for printf-style format strings.
24. GregorianCalendar: GregorianCalendar is a concrete subclass
of Calendar and provides the standard calendar system used by most
of the world.
25. HashMap<K,V>: Hash table based implementation of the Map
interface.
26. HashSet: This class implements the Set interface, backed by a hash
table (actually a HashMap instance).
27. Hashtable<K,V>: This class implements a hash table, which maps
keys to values.
28. IdentityHashMap<K,V>: This class implements the Map interface
with a hash table, using reference-equality in place of object-equality
when comparing keys (and values).
29. LinkedHashMap<K,V>: Hash table and linked list implementation
of the Map interface, with predictable iteration order.
30. LinkedHashSet: Hash table and linked list implementation of the
Set interface, with predictable iteration order.
31. LinkedList: Doubly-linked list implementation of the List and Deque
interfaces.
32. ListResourceBundle: ListResourceBundle is an abstract subclass of
ResourceBundle that manages resources for a locale in a convenient and
easy to use list.
33. Locale – Set 1, Set 2: A Locale object represents a specific
geographical, political, or cultural region.
34. Locale.Builder: Builder is used to build instances of Locale from
values configured by the setters.

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

Page 34

Downloaded by Thirumala Sarawad


Course II_BCA NEP Syllabus

35. Objects: This class consists of static utility methods for operating on
objects.
36. Observable: This class represents an observable object, or
“data” in the model- view paradigm.
37. PriorityQueue: An unbounded priority queue based on a priority
heap.
38. Properties: The Properties class represents a persistent set of
properties.
39. PropertyPermission: This class is for property permissions.
40. PropertyResourceBundle: PropertyResourceBundle is a concrete
subclass of ResourceBundle that manages resources for a locale using a
set of static strings from a property file.
41. Random: An instance of this class is used to generate a stream of
pseudorandom numbers.
42. ResourceBundle: Resource bundles contain locale-specific objects.
43. ResourceBundle.Control: ResourceBundle.Control defines a set of
callback methods that are invoked by the ResourceBundle.getBundle
factory methods during the bundle loading process.
44. Scanner: A simple text scanner which can parse primitive types and
strings using regular expressions.
45. ServiceLoader: A simple service-provider loading facility.
46. SimpleTimeZone: SimpleTimeZone is a concrete subclass of
TimeZone that represents a time zone for use with a Gregorian calendar.
47. Stack: The Stack class represents a last-in-first-out (LIFO) stack of
objects.
48. StringTokenizer: The string tokenizer class allows an application to
break a string into tokens.
49. Timer: A facility for threads to schedule tasks for future execution in
a background thread.
50. TimerTask: A task that can be scheduled for one-time or repeated
execution by a Timer.
51. TimeZone: TimeZone represents a time zone offset, and also
figures out daylight savings.
52. TreeMap<K,V>: A Red-Black tree based NavigableMap
implementation.
53. TreeSet: A NavigableSet implementation based on a TreeMap.
54. UUID: A class that represents an immutable universally unique
identifier (UUID).
55. Vector: The Vector class implements a growable array of objects.
56. WeakHashMap<K,V>: Hash table based implementation of the
Map interface, with weak keys.

Page 35

Downloaded by Thirumala Sarawad

You might also like