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

Java Unit-3

Uploaded by

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

Java Unit-3

Uploaded by

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

UNIT-III

INHERITANCE
1. What is inheritance?
Inheritance in Java is a mechanism in which one object acquires(inherits/derives) 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 you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and variables of
the parent class. Moreover, you can add new methods and variables in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Uses of inheritance in java
1. For Method Overriding (so runtime polymorphism can be achieved).
2. For Code Reusability.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
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.
Super Class/Parent Class: Super class is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
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.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality. In Java, a class which is
inherited is called a parent or superclass, and the new class is called child or subclass.
Java Inheritance Example
As displayed in the below figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.
1. /* Example Program on java inheritance */
2. class Employee{
3. float salary=40000;
4. }
5. class Programmer extends Employee{
6. int bonus=10000;
7. public static void main(String args[]){
8. Programmer p=new Programmer();
9. System.out.println("Programmer salary is:"+p.salary);
10. System.out.println("Bonus of Programmer is:"+p.bonus);
11. }
12. }
Output :
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java

2. Explain types of inheritance in java with examples?


In java, Inheritance is classified into five types. Those are listed below.
1. Single Inheritance
2. Multiple Inheritance (Through Interface)
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance (Through Interface)

Single Inheritance in Java


Single Inheritance is the simple inheritance of all, When a class extends another
class(Only one class) then we call it as Single inheritance. The below diagram represents the
single inheritance in java where Class B extends only one class Class A. Here Class B will be
the Subclass and Class A will be one and only Super class.

Single Inheritance Example


public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
Output:
disp() method of ClassA
disp() method of ClassB
Multiple Inheritance in Java
Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented Programming languages such
as Java, Small Talk, C# etc.. (C++ Supports Multiple Inheritance). As the Child class has
to manage the dependency of more than one Parent class. But you can achieve multiple
inheritances in Java using Interfaces.

Multilevel Inheritance in Java


In Multilevel Inheritance a derived class will be inheriting a parent class and as well
as the derived class act as the parent class to other class. As seen in the below diagram. ClassB
inherits the property of ClassA and again ClassB act as a parent for ClassC. In Short ClassA
parent for ClassB and ClassB parent for ClassC.
MultiLevel Inheritance Example
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}
Output: disp() method of ClassA
disp() method of ClassB
disp() method of ClassC
Hierarchical Inheritance in Java
In Hierarchical inheritance one parent class will be inherited by many sub classes. As
per the below example ClassA will be inherited by ClassB, ClassC and ClassD. ClassA will be
acting as a parent class for ClassB, ClassC and ClassD.
Hierarchical Inheritance Example
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();

//Assigning ClassD object to ClassD reference


ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA
Hybrid Inheritance in Java
Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface we can achieve
this. Flow diagram of the Hybrid inheritance will look like below. As you can ClassA will be
acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be acting
as Parent for ClassD.
3. 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.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{ //suppose if it were
8. Public Static void main(String args[]){
9. C obj=new C();
10. obj.msg(); //Now which msg() method would be invoked?
11. } 12. }
Output: Compile time error.
Method Overriding
4. Explain Method Overriding in Java ?
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
 Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. Method must have same name as in the parent class
2. Method must have same parameter as in the parent class.
3. Must be IS-A relationship (inheritance).
Example of method overriding
In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method is same
and there is IS-A relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6. public static void main(String args[]){
7. Bike2 obj = new Bike2();
8. obj.run();
9. }
Output: Bike is running safely
Final Keyword In Java
5. Explain final variable, final method, and final class in java?
The final keyword in java is used to restrict the user. The java final keyword can be used
in many contexts. Final can be:
1. Variable
2. Method
3. Class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.

Java final variable


If you make any variable as final, you cannot change the value of final variable (It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Output : Compile Time Error
Java final method
If you make any method as final, you cannot override it.
Example of final method
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4. class Honda extends Bike{
5. void run(){System.out.println("running safely with 100kmph");}
6. public static void main(String args[]){
7. Honda honda= new Honda();
8. honda.run();
9. }
10. }
Output : Compile Time Error
Java final class
If you make any class as final, you cannot extend it.
Example of final class
1. final class Bike{}
2. class Honda1 extends Bike{
3. void run(){System.out.println("running safely with 100kmph");}
4. public static void main(String args[]){
5. Honda1 honda= new Honda1();
6. honda.run();
7. }
8. }
Output : Compile Time Error

Abstract class & Method in Java


6. Explain about abstract class and abstract method in java using example?
1. Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
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.
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. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the
method.
Example of abstract class
abstract class A{}
2. Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example of abstract method
abstract void printStatus(); //no method body and abstract
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Test it Now

Output: running safely


Arrays
7. What is an array and Explain types of arrays with examples?
Normally, array is a collection of similar type of elements that have contiguous memory
location. Java array is an object the contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array


 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.
Disadvantage of Java Array
 Size Limit: We can store only 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.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array in java
An array stores similar type of elements in only one dimension at contiguous memory
locations is called single dimensional array.
Syntax to Declare an Array in java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in java
1.arrayRefVar=new datatype[size]; (or)
2.int a[]={33,3,4,5};//declaration, instantiation and initialization
Example of single dimensional java array
We can declare, instantiate and initialize the java array together by:
Let's see the simple example to print this array.
1. class Testarray1{
2. public static void main(String args[]){
3. int a[]={33,3,4,5};//declaration, instantiation and initialization
4. //printing array
5. for(int i=0;i<a.length;i++)//length is the property of array
6. System.out.println(a[i]);
7. }} Test it Now
Output: 33
3
4
5
Multidimensional array in java
An array which stores data in row and column based index (also known as matrix form) is called
multidimensional array.
Example :

Syntax to Declare Multidimensional Array in java


1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
int[][] arr=new int[3][3];//3 row and 3 column
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class Testarray3{
2. public static void main(String args[]){
3. //declaring and initializing 2D array
4. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
5. //printing 2D array
6. for(int i=0;i<3;i++){
7. for(int j=0;j<3;j++){
8. System.out.print(arr[i][j]+" ");
9. }
10. System.out.println();
11. }
12. }}
Test it Now
Output: 1 2 3
245
445
8. Explain about vectors in java with example?
Vector implements a dynamic array. Vector increments 100% means doubles the array
size if total number of element exceeds than its capacity. Vector uses Enumeration interface to
traverse the elements. But it can use Iterator also.
Example of Java Vector
Let's see a simple example of java Vector class that uses Enumeration interface.
1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }
13. }
14. }
Output: umesh
Irfan
kumar

9. Explain about wrapper classes in java with examples ?


Wrapper class in java provides the mechanism to convert primitive data type into
object and object into primitive type.Since J2SE 5.0, autoboxing and unboxing feature
converts primitive into object and object into primitive automatically. The automatic conversion
of primitive into object is known as autoboxing and vice-versa unboxing.
The eight classes of java.lang package are known as wrapper classes in java. The list of eight
wrapper classes are given below:
Primitive Type Wrapper class
Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Wrapper class Example: Primitive to Wrapper
1. public class WrapperExample1{
2. public static void main(String args[]){
3. //Converting int into Integer
4. int a=20;
5. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
6. System.out.println(a+" "+ j);
7. }}
Output : 20 20
Wrapper class Example: Wrapper to Primitive
1. public class WrapperExample2{
2. public static void main(String args[]){
3. //Converting Integer to int
4. Integer a=new Integer(3);
5. int j=a;//unboxing, now compiler will write a.intValue() internally
6. System.out.println(a+" "+j);
7. }}
Output : 3 3
Interface in Java
An interface is just like Java Class, but it only has static constants and abstract methods.
Java uses Interface to implement multiple inheritance.
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.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.Java Interface also represents the IS-A relationship.It cannot be
instantiated just like the abstract class.
How to declare 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.
}
In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.

The relationship between classes and interfaces

As shown in the figure given above, a class extends another class, an interface extends another
interface, but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.
1. interface printable{
2. final double pi = 3.14; //(Interface variable)
3. void print();
4. }
5. class A6 implements printable{
6. public void print(){System.out.println("Hello "+pi);}
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output: Hello 3.14
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. A7 obj = new A7();
12. obj.print();
13. obj.show();
14. }
15. }
Output: Hello
Welcome
Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
12. obj.print();
13. obj.show();
14. }
15. }
Test it Now
Output : Hello
Welcome

You might also like