Java Unit-Iv
Java Unit-Iv
class superclass-name
{
// body of class
}
class subclass-name extends superclass-name
{
// body of class
}
Example:
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)
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
}
}
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.
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");
}
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
}
}
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.
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
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;
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;
Page 8 of 26
{
width=w;
height=h;
depth=d;
}
OUTPUT
i in superclass:6
i in subclass:4
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();
r = a; // r refers to an A object
r= b; // r refers to a B object
r = c; // r refers to a C object
}
}
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
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
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:
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.
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.*;
Example:
import myPack.MyClass;
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.*;
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();
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:
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:
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
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();
}
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:
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:
Example:
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();
}
}
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:
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.
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
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:
Example:
class A
{
int i = 50;
@Override
protected void finalize() throws Throwable
{
System.out.println("From Finalize Method");
}
}
A a1 = new A();
A a2 = new A();
a1 = a2;
System.out.println("done");
}
}
Page 26 of 26