Java Unit 3
Java Unit 3
3.2 INHERITANCE:
3.2.1 Introduction
3.2.2 Process of Inheritance
3.2.3 Types of Inheritances
3.2.4 Universal Super Class- Object Class
3.2.5 Inhibiting Inheritance of Class Using Final
3.2.6 Access Control and Inheritance
3.2.7 Multilevel Inheritance
3.2.8 Application of Keyword Super
3.2.9 Constructor Method and Inheritance
3.2.10 Method Overriding
3.2.11 Dynamic Method Dispatch
3.2.12 Abstract Classes
3.2.13 Interfaces and Inheritance.
3.3 INTERFACES:
3.3.1 Introduction
3.3.2 Declaration of Interface
3.3.3 Implementation of Interface
3.3.4 Multiple Interfaces
3.3.5 Nested Interfaces
3.3.6 Inheritance of Interfaces
3.3.7 Default Methods in Interfaces
3.3.8 Static Methods in Interface
3.3.9 Functional Interfaces
3.3.10 Annotations
ADVANTAGES
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
DISADVANTAGES
Size Limit: We can store only the fixed size of elements in the array.
It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
TYPES OF ARRAY IN JAVA
There are two types of array.
Single Dimensional Array
Multidimensional Array
Initialization of an Array
Only the declaration of the array is not sufficient. In order to store values in the array, it is required to
initialize it after declaration. The syntax of initializing an array is given below.
datatype [] arrayName = new datatype [ size ]
ArrayExample1.java
public class ArrayExample1 {
public static void main( String args[] ) {
//initializing array without passing values
JAVA PROGRAMMING 2 KKVPRASAD@CSE
int[] array = new int[5];
//print each element of the array
for (int i = 0; i < 5; i++)
{
System.out.println(array[i]);
}} }
Output:
ArrayExample3.java
public class ArrayExample3 {
public static void main( String args[] ) {
int [] numbers = {22,33,44,55,66};
for (int i = 0; i < 5; i++)
{
System.out.println(numbers[i]);
}}}
Output:
The size or length of an array may be determined using the following code:
int arraySize = array_identifier.length;
The size of array numbers is determined as:
int size = numbers.length;
The elements of a large array may be accessed using a for loop.
For example, the elements of array numbers may be accessed as
for (int i = 0; i<size; i++)
System.out.println(x);
Example-1:
class NumArray
{
public static void main(String args[])
{
int numbers[] = new
int[4];numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
for(int i =0 ;i<numbers.length; i++)
System.out.println(numbers[i]);
}
}
Output:
10
20
30
40
Example: ArrayOperations.java
class ArrayOperations
{
public static void main(String args[])
{
int[] array1 = new int []{1,2,3,4,5};
System.out.println("Before Adding - Array elements are :"); display(array1);
//Passing an array to display() methodSystem.out.println();
// Operations on Arrays
for(int i =0; i< array1.length; i++)
array1[i] = array1[i] + 10; // Adding 10 to each element
System.out.println("After Adding - Array elements are :");
display(array1);
}
static void display(int[] array) //Method definition
{
for (int x : array) System.out.print(x + " ");
}}
Output:
Before Adding - Array elements are:
12 3 4 5
After Adding - Array elements are:
11 12 13 14 15
display(array1);
}
static void display(int[] array) //Method definition
{
for (int x : array)
System.out.print(x + " ");
}}
Output:
Before Changing Array Size: array1 =1 2 3 4 5
After Changing Array Size: array1 = 0 0 0 0 0 0 0 0 0
After Modification : array1 = 5 10 15 20 25 30 35 40 45 50
JAVA PROGRAMMING 6 KKVPRASAD@CSE
3.1.8 SORTING OF ARRAYS
Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort, insertion
sort, radix sort, bucket sort, etc but if we look closer here, we are not asked to use any kind of algorithms. It
is as simple sorting with the help of linear and non-linear data structures present within java. So there is
sorting done with the help of brute force in java with the help of loops and there are two in-built methods to
sort in Java.
1. Linear search
The method may be applied to any array.
The key value is compared to the value of the elements of the array successively.If a
match is found, it is noted, and the program ends there.
Otherwise, the complete array is searched, and if no match is found, it is reported that thevalue is
not there in the array.
public class LinearSearchExample{
JAVA PROGRAMMING 8 KKVPRASAD@CSE
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
} } return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
Output:
50 is found at index: 3
It is a very efficient method of search but it is applicable only to the sorted arrays.
The beginning, end, and the midpoint of the array are defined first.
The key value is compared with the value at midpoint.
If it does not match, then it is checked in which half of the array the key value lies by
checking whether the key value is more or less than the value at midpoint.
The array is truncated to the half in which the key value lies.
This process is repeated on that half, that is, it is again divided into two halves where thevalue is
compared with the midpoint;
if match is not found, it is determined in which half of the truncated array the value lies.
class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}}
Output:
Element is found at index: 2
JAVA PROGRAMMING 9 KKVPRASAD@CSE
3.1.10 CLASS ARRAYS
The Arrays class in java.util package is a part of the Java Collection Framework.
This class provides static methods to dynamically create and access Java arrays. It consists of only
static methods and the methods of Object class.
The methods of this class can be used by the class name itself.
The class hierarchy is as follows:
java.lang.Object
↳ java.util.Arrays
Some of the methods in Class Arrays
1: asList() Method
2: binarySearch() Method
3: binarySearch(array, fromIndex, toIndex, key, Comparator) Method
4: compare(array 1, array 2) Method
5: compareUnsigned(array 1, array 2) Method
6: copyOf(originalArray, newLength) Method
7: copyOfRange(originalArray, fromIndex, endIndex) Method
8: deepEquals(Object[] a1, Object[] a2) Method
9: equals(array1, array2) Method
10: mismatch(array1, array2) Method
11: sort(originalArray) Method
12: sort(originalArray, fromIndex, endIndex) Method
Example: ThreeDimArray.java
class ThreeDimArray{
public static void main(String[] args){
int num3D[][][]= { { {1,2,3},{4,5,6},{7,8,9}},
{ {11,12,13},{14,15,16},{17,18,19} }};
for(int[][] z: num3D){
for(int[]y : z){
for(int x : y) System.out.print( x + " ");
System.out.println();
}
System.out.println();
}}}
Output:
123
456
789
11 12 13
14 15 16
17 18 19
Advantages of Vectors.
Vectors are dynamically allocated, and therefore, they provide efficient memoryallocation.
Size of the vector can be changed as and when required.
They can store dynamic list of objects.
The objects can be added or deleted from the list as per the requirement.
Benefits of Inheritance
It allows the reuse of already developed and debugged class program without any
modification.
It allows a number of subclasses to fulfil the needs of several subgroups.
A large program may be divided into suitable classes and subclasses that may bedeveloped by
separate teams of programmers.
Disadvantages of Inheritance
The tight coupling between super and subclasses increases and it becomes very difficultto use
them independently.
Program processing time increases as it takes more time for the control to jumpthrough
various levels of overloaded classes.
When some new features are added to super and derived classes as a part ofmaintenance, the
changes affect both the classes.
When some methods are deleted in super class that is inherited by a subclass, the
methods of subclass will no longer override the super class method.
Example: SingleInheritance.java
class DemoA{
void displayA()
{
System.out.println("Super Class Method");
}
}
class DemoB extends DemoA{
void displayB()
{
System.out.println("Sub Class Method");
}
}
class SingleInheritance{
public static void main(String args[])
{
DemoA objA = new
DemoA();
objA.displayA();
DemoB objB = new
DemoB();
objB.displayB();
}
}
Output:
SingleInheritance
Super Class MethodSub Class Method
Example: Multilevel.java
class DemoA{
void displayA()
{
System.out.println("Class-A Method");
}}
class DemoB extends DemoA
{
void displayB()
{
System.out.println("Class-B Method");
}
}
class DemoC extends DemoB{
void displayC()
{
System.out.println("Class-C Method");
}
}
class Multilevel{
public static void main(String args[])
{
//calling class-A method DemoA objA = new DemoA();
objA.displayA();
//calling class-B method DemoB objB = new DemoB();
objB.displayB();
//calling class-C method DemoC objC = new DemoC();
objC.displayC();
}
}
Output:
Method Class-B Method Class-C Method
3. Hierarchical inheritance: In this type, one class is inherited by many sub classes.
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
class DemoB extends DemoA
{
void displayB()
{
System.out.println("Class-B Method");
}
}
class DemoC extends DemoA
{
void displayC()
{
System.out.println("Class-C Method");
}
}
class Heirarchical
{
public static void main(String args[])
{
//calling class-A
method DemoA
objA = new
DemoA();
objA.displayA();
DemoB objB = new DemoB();objB.displayB();
DemoC objC = new DemoC();
objC.displayC();
}
}
Output:
interface X
{
int x=10;
}
interface Y
{
int y=20;
}
class DemoA{
void displayA()
{
System.out.println("Class-A Method");
}
}
class DemoB extends DemoA implements X,Y
{
void displayB()
{
System.out.println("Class-B Method : x+y = " +(x+y));
}
}
class Multiple
{
public static void main(String args[])
{
DemoA objA = new DemoA();objA.displayA();
DemoB objB = new DemoB();objB.displayB();
}
}
Output:
Class-A Method
Class-B MethodClass-C Method
Example:ObjectEquals.java
class DemoA{
void displayA(){
System.out.println("Class-A Method");
}
}
class ObjectEquals
{
public static void main(String args[])
{
DemoA obj1 = new DemoA();
DemoA obj2 = new DemoA();
boolean test;
//Checking - if both object are equal
test = obj1.equals(obj2);
display(test);
// Object assignment
obj1=obj2;
//Checking - if both object are equal after assigning theobjects
test = obj1.equals(obj2);
display(test);
}
public static void display(boolean test)
{
Output:
Both objects are different
Both objects are same
Example:FinalClass.java
final class A
{
int a;
A(int x) {a=x;}
void display()
{
System.out.println("a = "+ a);
}
}
class B extends A
{
int b;
B(int x,int y)
{
super(x);this.b=y;
}
void display()
{
System.out.println("b = "+ b);
}
}
class FinalClass
{
public static void main (String args[])
{
A objA= new A(10);
B objB= new B(100,200);
objA.display();
objB.display();
}
}
Output:
JAVA PROGRAMMING 19 KKVPRASAD@CSE
C:\>javac FinalClass.java
FinalClass.java:11: error: cannot inherit from final Aclass B extends A
^
1 error
Example-1: DefaultAccess.javaclass
DemoA
{
int a;
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class DemoB extends DemoA
{
int b;
void displayB()
{
System.out.println("Class-B Method : a = " + a + " b = " + b );
}
}
class DefaultAccess
{
public static void main(String args[])
}
}
Output:
C:\>javac DefaultAccess.java
C:\>java DefaultAccess
Class-A Method : a = 100
Class-B Method : a = 200 b = 300
class DemoA
{
private int a;DemoA(int
x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class DemoB extends DemoA
{
int b;
DemoB(int p, int q)
{
super(p);b=q;
}
void displayB()
{
displayA();
System.out.println("Class-B Method : b = " + b );
}
}
class PrivateAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA(150);
//objA.a=100; // Error, Can't access private variable
objA.displayA();
//calling class-B method
Example: ProtectedAccess.java
class DemoA
{
protected int a;DemoA(int t)
{
a = t;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class DemoB extends DemoA
{
int b;
DemoB(int p, int q)
{
super(p);b=q;
}
void displayB()
{
System.out.println("Class-B Method : a= " + a + " b = " + b );
}
}
class DemoC extends DemoB
{
int c;
DemoC(int x, int y, int z)
{
super(x,y);c=z;
}
void displayC()
{
System.out.println("Class-B Method : a = " + a + " b = " + b +" c = " + c);
}
}
class ProtectedAccess
{
public static void main(String args[])
{
//calling class-A method DemoA objA = new
DemoA(100);
//objA.a=100; // Error, Can't access protected variableobjA.displayA();
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();
}}
Output:
weeping...
barking...
eating...
class A
{
int a;
A(int x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class B extends A
{
int b;
B(int p, int q)
{
super(p); // Calling Super class Construtorb=q;
}
void displayB()
{
// Refering Super class with super keyword
System.out.println("Class-B Method : a = " + super.a + " b = " + b );
}
}
class SuperDemo
{
public static void main(String args[])
{
//Creating class B object by calling sub class constructor
B objB = new B(500,1000);
}
}
Output:
Class-B Method : a = 500 b = 1000
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.
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.
OrderofExecution1.java
class ParentClass
{
ParentClass()
{
System.out.println("ParentClass constructor executed.");
}
}
class ChildClass extends ParentClass
{
ChildClass()
{
System.out.println("ChildClass constructor executed.");
}
}
public class OrderofExecution1
{
public static void main(String ar[])
{
System.out.println("Order of constructor execution...");
new ChildClass();
}}
Output:
Order of constructor execution...
ParentClass constructor executed.
ChildClass constructor executed.
Example: MethodOverriding.java
class A
{
void display()
{
System.out.println("Super Class Method");
}
}
class B extends A
{
void display()
{
System.out.println("Sub Class Method");
}
}
class MethodOverriding
{
public static void main(String args[])
{
//calling the class A methodA objA = new A();
objA.display();
Abstract class: is a restricted class that cannot be used to create objects (to access it,it must
be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body.The
body is provided by the subclass (inherited from).
Example: Abstract.java
abstract class A
{
int a;
void setValue(int x)
{
a=x;
}
abstract void display();
}
class B extends A
{
int b;
void setValues(int x, int y)
{
a=x;b=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " b = " + b);
}
}
class C extends A
{
int c;
void setValues(int x, int y)
{
a=x;c=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " c = " + c);
}
}
class Abstract
{
public static void main(String args[])
{
JAVA PROGRAMMING 27 KKVPRASAD@CSE
//calling class-B method
System.out.println("Through objB");
B objB = new B();
objB.setValues(10,20);
objB.display();
//calling class-C method
System.out.println("Through objC");
C objC = new C();
objC.setValues(150,250);
objC.display();
}
}
3.2.12 INTERFACES AND INHERITANCE.
Multiple inheritance of classes is not permitted in Java.
To some extent, this restriction can be overcome through interfaces.
A class may implement more than one interface besides having one super class.
An interface can extend one or more interfaces, and a class can also implement morethan one
interface.
An interface is a collection of constants and abstract methods that are implemented by aclass.
An interface cannot implement itself like a class;
An interface just contains the method head, and there is no method body. The class that
implements the interface contains the full definition of the method.
import java.io.*;
class Parent1 {
void fun() {
System.out.println("Parent1");
}}
class Parent2 {
void fun() {
System.out.println("Parent2");
}}
class Test extends Parent1, Parent2 {
Multiple inheritance is not supported by Java using classes, handling the complexity that causes due
to multiple inheritances is very complex. It creates problems during various operations like casting,
constructor chaining, etc, and the above all reason is that there are very few scenarios on which we actually
need multiple inheritances, so better to omit it for keeping things simple and straightforward.
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.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Internal addition by the compiler
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.
In this example, the Printable interface has only one method, and its implementation is provided in
the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone else.
The implementation part is hidden by the user who uses the interface.
File: TestInterface1.java
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
An interface, i.e., declared within another interface or class, is known as a nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested
interface must be referred to by the outer interface or class. It can't be accessed directly.
Java provides a facility to create default methods inside the interface. Methods which are defined
inside the interface and tagged with default are known as default methods. These methods are non-abstract
methods.
interface Sayable{
default void say(){
System.out.println("Hello, this is default method");
}
// Abstract method
void sayMore(String msg);
}
public class DefaultMethods implements Sayable{
An Interface that contains exactly one abstract method is known as functional interface. It can have
any number of default, static methods but can contain only one abstract method. It can also declare
methods of object class.
Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. It is a
new feature in Java, which helps to achieve functional programming approach.
3.3.10 ANNOTATIONS
Annotations are used to provide supplemental information about a program.
Annotations start with ‘@’.
Annotations do not change the action of a compiled program.
Annotations help to associate metadata (information) to the program elements i.e. instance
variables, constructors, methods, classes, etc.
Annotations are not pure comments as they can change the way a program is treated by the
compiler.
Annotations basically are used to provide additional information, so could be an alternative to
XML and Java marker interfaces.
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}
JAVA PROGRAMMING 34 KKVPRASAD@CSE
3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
} }
*****