0% found this document useful (0 votes)
47 views26 pages

Java Unit-Iv

The document covers the concepts of inheritance, packages, and interfaces in Java. It explains different types of inheritance such as single, multiple (through interfaces), multilevel, hierarchical, and hybrid inheritance, along with examples. Additionally, it discusses method overriding, the use of the super keyword, dynamic method dispatch, the Object class, and the creation and importing of packages 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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views26 pages

Java Unit-Iv

The document covers the concepts of inheritance, packages, and interfaces in Java. It explains different types of inheritance such as single, multiple (through interfaces), multilevel, hierarchical, and hybrid inheritance, along with examples. Additionally, it discusses method overriding, the use of the super keyword, dynamic method dispatch, the Object class, and the creation and importing of packages 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 PDF, TXT or read online on Scribd

UNIT-IV

Inheritance, Packages & Interface


Inheritance
 Inheritance in java is a mechanism in which one object acquires all the properties and
methods of parent object.
 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 fields of parent
class, and you can add new methods and fields also.
 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 the terminology of Java, a class which is inherited is called parent or super class and
the new class is called child or subclass.
 Syntax:

class superclass-name
{
// body of class
}
class subclass-name extends superclass-name
{
// body of class
}

 Example:

// A simple example of inheritance.

Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

Types of Inheritance

Que:
1. List different types of inheritance and explain any one with example.
2. Describe different forms of inheritance with example.
3. List types of Inheritance in Java.
4. Explain multilevel inheritance with example.
5. List four types of Inheritance.
Ans:
 Below are the different types of inheritance which is supported by Java.

1. Single Inheritance
2. Multiple Inheritance (Through Interface)
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance (Through Interface)

1. 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 Sub class and Class A will be one and only Super class.

Class A
Page 2 of 26
{
public void methodA()
{
System.out.println("Base class method");
}
}

class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

2. Multiple Inheritance in Java

 In Multiple Inheritance, 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.
 Java does not support multiple inheritance because the Child class has to manage the
dependency of more than one Parent class.
 But you can achieve multiple inheritance in Java using Interfaces.

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

Page 3 of 26
 As seen in the below diagram. Class B inherits the property of Class A and
again Class B act as a parent for Class C. In Short Class A parent for Class
B and Class B parent for Class C.

 MultiLevel Inheritance Example

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

public static void main(String args[])

Page 4 of 26
{
C obj = new C();
obj.methodA(); //calling grandparent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling local method
}
}

4. Hierarchical Inheritance in Java

 In Hierarchical inheritance one parent class will be inherited by many sub classes.
 As per the below example Class A will be inherited by Class B, Class C and Class
D. Class A will be acting as a parent class for Class B, Class C and Class D.

 Hierarchical Inheritance Example

public class A
{
public void methodA()
{
System.out.println("Class A method ");
}
}
public class B extends A
{
public void methodB()
{
System.out.println("Class B method ");
}
}
public class C extends A
{
public void methodC()
{
System.out.println("Class C method ");
}
Page 5 of 26
}
public class D extends A
{
public void methodD()
{
System.out.println("Class D method ");
}
}
public class HInheritance
{
public static void main(String args[])
{
B b = new B();
b. methodB();
b. methodA();

C c = new C();
c. methodC();
c. methodA();

D d = new D();
d. methodD();
d. methodA();
}
}
5. 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 Class A will be acting as the Parent class for Class B & Class
C and Class B & Class C will be acting as Parent for Class D.

Page 6 of 26
Method Overriding
 When a method in a sub class has same name and type signature as a method in its super
class, then the method in the sub class is said to overriding the method in the super class.
 When an overridden method is called from within a sub class, it will always refer to
method defined by the sub class.
 The method defined by the super class will be hidden.
class A
{
int i, j;

A(int a, int b)
{
i = a;
j = b;
}

void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;

B(int a, int b, int c)


{
super(a, b);
k = c;
}
Page 7 of 26
void show()
{
System.out.println("k: " + k);
}
}

public class MultiOverride


{
public static void main(String args[])
{
B b=new B(10,20,30);

b.show(); //calls show method of class B by overriding show method in class A


}
}

Output:
k: 10

Super Keyword
Que:
1. Write a Java Program to explain super keyword.
2. Explain Super keyword in inheritance.
3. State the importance of super keyword in Java.
Ans:
 Super keyword is used by subclass to refer to its immediate superclass.
 Super class also known as Base class.
 Super keyword has two uses:
1.To call the super class constructor
 Using Super keyword, a subclass can call a constructor defined by its superclass.
 Constructors are called in order of derivation from super class to sub class.
 Syntax:
Super(arg-list);
 Here,arg-list specifies any arguments needed by the constructor in the superclass.
 Super() must always be the first statement executed inside a subclass constructor.
 Example
class Box
{
double width;
double height;
double depth;

Box (double w, double h, double d)

Page 8 of 26
{
width=w;
height=h;
depth=d;
}

class BoxWeight extends Box


{
double weight;

BoxWeight(double w, double h, double d, double m)


{
super(w, h, d); // call superclass constructor
weight = m;
}
}

2. To access a member of the superclass


 When member names of a subclass and superclass are same then member names of a
sub class hide same members of the superclass.
 In this situation, Super keyword is used to access the super class member.
 Syntax:
Super.member
 member can be either a method or an instance variable.
 Example
Class A
{
int i;
}
Class B extends A
{
int i;
B(int a,int b)
{
Super.i=a;
i=b;
}
Void show()
{
System.out.println(“i in superclass:”+super.i);
System.out.println(“i in subclass:”+ i);
}
}
Class usesuper
Page 9 of 26
{
Public static void main(String args[])
{
B ob=new B(6,4);
ob.show();
}
}

OUTPUT
i in superclass:6
i in subclass:4

Dynamic Method Dispatch


 Dynamic method dispatch is the mechanism by which a call to an overridden method
is resolved at runtime,rather than comile time. This is the way, java implements
runtime polymorphism.
 Dynamic method dispatch uses the prinicpal: “Super class reference variable refers to a
sub class object”.
 When an overridden method is called by a super class reference, java determines which
version of that method to execute based on the type of object it refer to.
 In simple words, the type of object which it referred determines which version of
overridden method will be called.
 Example:

class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()

void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()

Page 10 of 26
void m1()
{
System.out.println("Inside C's m1 method");
}
}

class Dispatch
{
public static void main(String args[])
{
A a = new A();

B b = new B();

C c = new C();

A r; // obtain a reference of type A

r = a; // r refers to an A object

r. m1(); // calling A's version of m1()

r= b; // r refers to a B object

r.m1(); // calling B's version of m1()

r = c; // r refers to a C object

r.m1(); // calling C's version of m1()

}
}

Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method

Object class in Java


 The Object class is the parent class of all the classes in java by default. In other words,
it is the superclass of all other class.
 A reference variable of type Object can refer to an object of any other class.
 Object class provides following methods:

Page 11 of 26
Method Purpose
getClass() Obtains the class of an object at run time.
clone() Creates and returns a copy of this object.
equals() Indicates whether some other object is "equal to" this one.
finalize() Called by the garbage collector on an object when garbage
collection determines that there are no more references to the
object.
getClass() Returns the runtime class of an object.
hashCode() Returns a hash code value for the object.
notify() Wakes up a single thread that is waiting on this object's
monitor.
notifyAll() Wakes up all threads that are waiting on this object's monitor.
toString() Returns a string representation of the object.
wait() Causes current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.

Package
Que:
1. Explain packages.
2. Define package and interface.
3. List out the steps to create a package.
4. Write the syntax to create and import a package.
5. Write the steps to create user defined package.
6. Define Package in Java.
7. State the name of any four inbuilt Java package.
8. Explain concept of user defined package in brief.
Ans:

 Definition: 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.
 User-defined packages: These are the packages that are defined by the user.
Creating a Package

 To create package in java is quite easy; simply include a package command as the first
statement in a java source file.
 There can be only one package statement in each source file.
 Any classes declared within that file will belong to the specified package.

Page 12 of 26
 Package statement defines a name space in which classes are stored.
 If a package statement is not used in the class, the class names are put into the default
package.
 Syntax of Defining a Package :
package pkg; //here,pkg is package name

E.X. package mypack;


 We can also create hierarchy of packages. simply separate each package name from the
one above it by use of a period.
 The general form of a multileveled package statementis shown here:
package pkg1[.pkg2[.pkg3]];

package java.awt.image;
Compile and Run Package Program

 First we create a directory myPackage. Name should be same as the name of the
package.
 MyClass.java must be saved inside the myPackage directory since it is a part of the
package.
 MyClass.java must include “package myPackage” as first statement.

package myPack;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
To compile java package Program:

> javac -d directory javafilename

For example

>javac -d . MyClass.java

 The -d switch specifies the destination where to put the generated class file.
 You can use any directory name like, d:/abc etc. If you want to keep the package
within the same directory, you can use . (dot).
Page 13 of 26
To run java package program

 We need to use fully qualified name e.g. mypack.Simple etc to run the class.

> java mypack.Simple

Importing Packages
 The import keyword is used to make the classes and interface of another package
accessible to the current package.
 Import statement must be after package statement (if it exists) and before class
deifnition.
 Syntax:
Import pkg1[.pkg2].(classname|*);

Here,pkg1 is the name of top-level package and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.).

Import MyPack.*;

 When a package is imported,only those members within packages declared as public


can be accessed by importing code.

 Example:

/* import 'MyClass' class from myPackage */

import myPack.MyClass;

public class PrintName


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

String name = "Java Programming";

MyClass obj = new MyClass(); // Creating an object of class MyClass in the


package.

obj.getNames(name);
}
}

Page 14 of 26
Features/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.

Built-in Packages
 These packages consist of a large number of classes which are a part of Java API.
 Some of the commonly used built-in packages are:
1. java.lang:
o Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2. java.io:
o Contains classed for supporting input / output operations.
3. java.util:
o Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4. java.applet:
o Contains classes for creating Applets
5. java.awt:
o Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6. java.net:
o Contain classes for supporting networking operations.

Access Modifiers
Que:
1. Explain different visibility controls used in Java.
2. Write short note: Access Protection .
3. Explain different Access Controls in Java.
4. Discuss the various levels of protection available for packages & their implications.
Ans:

 As the name suggests access modifiers in Java helps to restrict the scope of a class,
constructor , variable , method or data member.
 There are four types of access modifiers available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

1. Default:
 When no access modifier is specified for a class, method or data member. It is said to
be the default access modifier by default.

Page 15 of 26
//Java program to illustrate default modifier

package p1;

class Geek
{
void display()
{
System.out.println("Hello World!");
}
}

package p2;
import p1.*;

//This class is having default access modifier


class GeekNew
{
public static void main(String args[])
{

Geeks obj = new Geek();

obj.display();
}
}
2. Private:
 The private access modifier is specified using the keyword private.
 The methods or data members declared as private are accessible only within the class
in which they are declared.
 Any other class of same package will not be able to access these members.
 Classes or interface can not be declared as private.
 In this example, we will create two classes A and B within same package p1. We will
declare a method in class A as private and try to access this method from class B and
see the result.

package p1;

class A
{
private void display()
{
System.out.println("GeeksforGeeks");
}
Page 16 of 26
}

class B
{
public static void main(String args[])
{
A obj = new A();

obj.display(); //Shows Error


}
}

3. protected:
 The protected access modifier is specified using the keyword protected.
 The methods or data members declared as protected are accessible within same
package or sub classes in different package.
 In this example, we will create two packages p1 and p2. Class A in p1 is made public,
to access it in p2. The method display in class A is protected and class B is inherited
from class A and this protected method is then accessed by creating an object of class
B.

package p1;

//Class A
public class A
{
protected void display()
{
System.out.println("GeeksforGeeks");
}
}
Run on IDE

package p2;
import p1.*; //importing all classes in package p1

//Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

}
Page 17 of 26
4. public:
 The public access modifier is specified using the keyword public.
 Classes, methods or data members which are declared as public are accessible from
every where in the program.
 There is no restriction on the scope of a public data members.

package p1;
public class A
{
public void display()
{
System.out.println("GeeksforGeeks");
}
}
package p2;
import p1.*;
class B
{
public static void main(String args[])
{
A obj = new A;
obj.display();
}
}

Page 18 of 26
INTERFACE
Que:
1. What is interface?
2. Explain with example how multiple inheritance can be implemented by interface.
3. Define interface in Java.
4. Explain how to implement multiple inheritances in java through interface?
5. Explain interface in Java.
6. Explain Interface concept with example.
Ans:

 An interface is a collection of abstract methods (i.e. methods without having


definition).
 Interface specifies what a class must do,but not how it does it.
 Each class that includes an interface must implement all of the methods.
 One class can implement any number of interfaces.
 Defining an Interface
 Interface is defined muchlike a class.
 This is the general form of an interface.

Access interface name


{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);

type final-varname1 = value;


type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

 The access modifier is either public or no modifier.


 When interface is declared public, it is used anywhere and when its declared with no
modifier than it can be used only in a package in which it is declared.
 Name is the name of the interface.
 All methods of an interface are abstract methods. It means without its bodies.
 All method end with a semicolon after the parameter list.
 Variables can be declared inside interface. They are implicitly final and static,
meaning they cannot be changed by the implementing class. They must also be
initialized.
 All methods and variables are implicitly public.

Implementing Interfaces
 Once an interface has been defined, one or more classes can implement that interface.
 To implement an interface, include the implements clause in a class definition, and
then create the methods defined by the interface.
Page 19 of 26
 The general form of a class that includes the implementsclause looks like this:

Access class classname[extends superclass] [implements


interface [,interface...]]
{
// class-body
}

 For Example,
interface Callback
{
void callback(int param);
}
class Client implements Callback
{
public void callback(int p) // Implement Callback's interface
{
System.out.println("callback called with " + p);
}
}
classTestIface
{
public static void main(String args[])
{
Client c = new Client();
c.callback(42);
}
}

 OUTPUT:
callback called with 42

multiple inheritance using interface

 Class can implements more than one interface. so we can create multiple inheritance
by implementing more than one interface.

interface i1
{
void print();
}

interface i2
Page 20 of 26
{
void show();
}

public class demo implements i1,i2


{
public void print()
{
System.out.println("hello from i1");
}
public void show()
{
System.out.println("hello from i2");
}
public void display()
{
System.out.println("hello ");
}
}
Class InterfaceDemo
{
public static void main(String[] args) {

demo obj =new obj();


obj.print();
obj.show();
}
}

Similarities and Differences between Class and Interface


 The similarities are between Class and Interface are as below:

1) They both can contain variables and methods. (With difference being class methods
have implementation code whereas the interface methods can only have declarations)
2) They can both be inherited using Inheritance. (extends keyword for classes and
implements keyword for interfaces)
 difference between class and interface are as below:

Sr. No Interface Class


We cannot instantiate (i.e. create we can instantiate a class
1
object) an interface
All the methods in an interface are All the methods of class are not
2
abstract (i.e. without definitions) abstract.
Page 21 of 26
The variable is static and final. class can contain any type of variable
3
An interface can extend multiple Class can not extend multiple classes
interfaces (i.e. multiple (i.e multiple inheritance can not be
4
inheritances can be achieved achieved).
through it).

Abstract class
Que:
1. Differentiate Abstract class and Interface.
2. Explain Abstract Keyword with example.
3. Explain how abstract class differs from final class.
4. Define Abstract class.
5. Explain Abstract class in Java.
6. Explain abstract and final keywords with example.
Ans:

 A class that is declared with abstract keyword, is known as abstract class.


 It can have abstract and non-abstract method.
 An abstract method is a method that is declared without an implementation.
 If a class has at least one abstract method, then the class must be declared abstract.
 It is not possible to create object of an abstract class.
 To use an abstract class, we have to inherit abstract from another class.
 If we inherit an abstract class, we have to provide implementations to all the abstract
methods in it.
 Syntax:
abstract class class-name
{
abstract type-name(parameter-list); //abstract Method

type-name(parameter-list) //Non-Abstract Methods;


{
//statements;
}
}

 Example:

// A Simple demonstration of abstract.

abstract class A
{
abstract void callme();

void callmetoo()

Page 22 of 26
{
System.out.println("This is a concrete method.");
}
}
Class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}

Difference between Interface and abstract class


Que:
1. Compare following:
(i) Abstract Class Vs Interfaces
Ans:
Abstract class Interface
1 Abstract class contains abstract Interface contains only Absrtact methods.
methods and Non-Abstract Methods. Java-8 also use default and static
methods.
2 abstract keyword is used to create an interface keyword is used to create
abstract class interface
3 Subclasses use extends keyword to subclasses use implements keyword to
extend an abstract class. implement interfaces.
4 Abstract classes can have constructors. interfaces can’t have constructors.
5 Abstract classe methods can have interface methods are implicitly public.
access modifiers as public, private,
protected, static
6 A subclass can extend only one abstract A subclass can implement more than one
class. interface.
7 Syntax: Syntax:
abstract class name Interface name
{ {
//abstract and Non-Abstract Methods //abstract method
} }

Page 23 of 26
Final Keyword
Que:
1. When do we declare a method or class as final.
2. Explain final keyword with example.
3. Define Final keyword in java.
Ans:
 The keyword final has three users.
1. It can be used to create equivalent of named constants.
2. It also can used to prevent inheritance.
3. It can used to prevent overriding.

1.Final Variable
 A variable can be declared with the use of final keyword then it is known as ‘Final
Variable’.
 To prevent the contents of variable from being modified then assign that variable as
Final Variable.
 This means that you must initialize a final variable when it is declared.
 In C/ C++, we have to use const keyword for define constant variable, whether in Java
we are using final keyword to define as constant.
 To define Constant:

final datatype variable=value;

final int PI=3.14


 It is a common coding convention to choose all uppercase identifiers for final
variables.
 Variables declared as final do not occupy memory on a per-instance basis. Thus, a
final variable is essentially a constant.

2.Final Class
 Sometimes you will want to prevent a class from being inherited. To do this, precede
the class declaration with final.
 Declaring a class as final implicitly declares all of its methods as final, too.
 As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its sub classes to provide complete
implementation.
 here is an example of a final class:

Final class A
{
// ...
}
// the following class is illegal.
Page 24 of 26
Class B extends A
{
// ERROR! Can't subclass A
// ...
}
 As the comments imply, it is illegal for B to inherit A since A is declared as final.

3.Using Final to Prevent Overriding


 While method overriding is one of Java’s most powerful features, there will be times
when you will want to prevent it from occurring.
 To disallow a method from being overriding, specify final as a modifier at the
start of its declaration. Methods declared as final can’t be overridden.

Example:

Class A
{
A ()
{
final void meth ()
{
System.out.println (“This is Final Method.”);
}
}
}
Class B extends A
{
Void meth () //Error:= Can’t Override
{
System.out.println (“Illegal”);
}
}

Garbage Collection

 Memory allocated to object released automatically in java is called Garbage collection.


 It is the process by which Java programs perform automatic memory management.
 When Java programs run on the JVM, objects are created in the memory.
 When there are no references to an object, it is assumed to be no longer needed.
 The garbage collector finds these unused objects and deletes them to free up memory.

finalize method

 finalize method is a method that the Garbage Collector always calls just before the
deletion of the object.
Page 25 of 26
 This method is used to perform some final operations or clean up operations on an
object before an object is destroyed.
 Here is the general form of finalize() method:

protected void finalize( )


{
//Keep some resource closing operations here

 Example:
class A
{
int i = 50;

@Override
protected void finalize() throws Throwable
{
System.out.println("From Finalize Method");
}
}

public class Test


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

A a1 = new A();

A a2 = new A();

a1 = a2;

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

Page 26 of 26

You might also like