Unit 2
Unit 2
Unit 2
Constructor, Overloading, Garbage Collector, Importance of Static Keyword and this keywords,
Examples, Arrays, Command Line Arguments, Nested Classes.
Packages: Defining a Package, PATH, CLASSPATH, Difference between PATH and CLASS
PATH, Access protection, importing packages.
Aim& objectives:
Constructors are special function which is called automatically when we create object of
the class.
Inheritance for the sole purpose of code reusability.
The primary concern is that implementation inheritance does not provide any assurance
of polymorphic substitutability—an instance of the reusing class cannot necessarily be
substituted for an instance of the inherited class.
Usage of arrays ,constructors in java coding
De allocation of memory in garbage collection
Passing values through command line
Constructors:
In which constructor has the same name as class name. That is for example let us assume
a class with name Student the constructor of that class is as follows
Student( )
{
}
Constructor has no return type even void. This is because the implicit return type of a
class’ constructor is the class type itself.
Constructor is automatically called and executed at the time of creating an object. While
creating an object, if nothing is passed to the object, the default constructor is called and
executed. If some values are passed to the object, then the parameterized constructor is
called.
For example
Student s=new Student(); //Which invokes default constructor
Student s=new Student(name,28); // Which invokes default constructor
Constructor is called and executed only once per object. This means when we create an
object, the constructor is called. When we create second object, again the constructor is
called second time.
Types of constructors
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter. If you
don’t implement any constructor in your class, the Java compiler inserts default constructor
into your code on your behalf. You will not see the default constructor in your source
code(the .java file) as it is inserted during compilation and present in the bytecode(.class
file).
<class_name>()
//instance variables
String name:
int rno;
//defaul t constr uct or
Student()
{
name= "Abhi";
rno=2;
}
/ /method
void study()
{
System.out.println("My name is "+ name);
System.out. println(“My roll no is "+ rno) ;
}
}
class ConDemo
{
public static void main (string args[ ])
{
//creating object one
Student one = new Student();
//call the study() method
one. study();
/ /create another object two
Student two= new Student();
//call the study() method
two. study();
}
}
Output:
C:\> javac ConDemo.java
C:\>java ConDemo
My name is Abhi
My roll no is 2
My name is Abhi
My roll no is 2
In the above example the objects have same values. To solve the problem let us try
parameterized constructor which accepts data from outside and initializes
instance variables with that data. Let us understand with an example.
Parameterized constructor
The parameterized constructor is used to provide different values to the distinct objects.
However, you can provide the same values also.
class Student
//instance variables
String name:
int rno;
//default t constructor
Student()
{
name= "Abhi";
rno=2;
}
//parameterized constructor
Student(String a,int b)
{
name= a;
rno=b;
}
/ /method
void study()
{
System.out.println("My name is "+ name);
System.out. println(“My roll no is "+ rno) ;
}
}
class ConDemo
{
public static void main (string args[ ])
{
//creating object one
Student one = new Student();
//call the study() method
one. study();
/ /create another object two
Student two= new Student(“Ravi”,5);
//call the study() method
two. study();
}
}
Output:
C:\> javac ConDemo.java
C:\>java ConDemo
My name is Abhi
My roll no is 2
My name is Ravi
My roll no is 5
Constructor-overloading
In Java it is possible to define two or more class constructors that share the same name, as long
as their parameter declarations are different. This is called constructor overloading when an
overloaded constructor is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded constructor to actually call. Thus, overloaded
constructors must differ in the type and/or number of their parameters
class Area{
double length;
double breadth;
// constructor used when all dimensions specified
Area(double l, double b, ) {
length = l;
breadth = b;
}
// constructor used when no dimensions specified
Area() {
length=1;
breadth=1;
}
// constructor with one parameter
Area(double len) {
Length=breadth = len;
}
// compute and return area of
double Areacal() {
return length*breadth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// invoking constructors
Area a1 = new Area(5,4);
Area a2= new Area(3);
Area a3 = new Area();
double area;
// get area of rectangle
area= a1.Areacal();
System.out.println("Area of rectangle is " + area);
// get area of square
area= a2.Areacal();
System.out.println("Area of square is " + area);
// get area of another square
area=a3.Areacal();
System.out.println("Area of another square is " + area);
}
Output:
The output produced by this program is shown here:
Area of rectangle is 20.0
Area of square is 9.0
Area of another square is 1.0
Garbage Collection
Since objects are dynamically allocated by using the new operator, you might be wondering how
such objects are destroyed and their memory released for later reallocation. In some languages,
such as C++, dynamically allocated objects must be manually released by use of a delete
operator. Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.It works like this: when no
references to an object exist, that object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed. There is no explicit
need to destroy objects as in C++. Garbage collection only occurs during the execution of your
program. The main job of this is to release memory for the purpose of reallocation. Furthermore,
different Java run-time implementations will take varying approaches to garbage collection
The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed. For example,if an
object is holding some non-Java resource such as a file handle or character font, then you might
want to make sure these resources are freed before an object is destroyed. To handle such
situations, Java provides a mechanism called finalization. By using finalization, you can define
specific actions that will occur when an object is just about to be reclaimed by the garbage
collector. To add a finalize to a class, you simply define the finalize( ) method. The Java run time
calls that method whenever it is about to recycle an object of that class. Inside the finalize( )
method, you will specify those actions that must be performed before an object is destroyed. The
garbage collector runs periodically, checking for objects that are no longer referenced by any
running state or indirectly through other referenced objects The finalize( ) method has this
general form:
protected void finalize ( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
Let us take an example
//example for garbage collection manually
Class Garb
{
protected void finalize ()
{
System.out.println(“Object is garbage collected”);
}
Public static void main(String args[])
{
Garb a1=new Garb();
Garb a2=new Garb();
a1=null;
a2=null;
System.gc();
}
}
Output:
In the above example null is used to remove the reference to object manually
static variables
static variable is common to all the instances (or objects) of the class because it is a class level
variable. In other words you can say that only a single copy of static variable is created and shared
among all the instances of the class. Memory allocation for such variables only happens once when
the class is loaded in the memory.
Like variables we can have static block, static method and static class.
Static variable Syntax
static keyword followed by data type, followed by variable name.
static variables are shared among all the instances of the class, they are useful when we need to do
memory management. In some cases we want to have a common value for all the instances like
global variable then it is much better to declare them static as this can save memory
example
class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:
Static Methods:
static Block:
static block is a block of statements declared as static
static {
code;
}
JVM first looks for static block then only main will be executed. Static block has highest priority
Output:
C:/javac Ss.java
C:/>java Ss
First executes Static block
Next Static method
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. This is the instance of current class. That is, this is always a reference to the
object on which the method was invoked. You can use this any where a reference to an object of
the current class’ type is permitted, this is used to refer constructor instance variables and
methods of current class.
Instance variables
this Constructor
Methods
In the above example this is used to refer default,parametrised constructor i.e. Thisdemo(),
Thisdemo(String a),method i.e. Branch(),instance variable i.e. a.
Arrays
An Array is a collection of elements of same type. The elements share the same name which can
be accessed by the index. To create an array, we must first create the array variable of the desired
type.
one dimensional array
A list of items group in a single variable name with only one index is called 1-D array.
1. creating an array
We can declare an array in java using subscript operator
datatype var_name[ ];
numbers
Element 0 0 0 0 0 0 0 0 0 0
index 0 1 2 3 4 5 6 7 8 9
After this statement executes, numbers will refer to an array of 10 integers. Further, all
elements in the array will be initialized to zero.
Once you have allocated an array, you can access a specific element in the array by
specifying its index within square brackets. All array indexes start at zero. For example,
this statement assigns the value 5 to the first element of numbers.
numbers[0] = 5;
Element 5 0 0 0 0 0 0 0 0 0
index 0 1 2 3 4 5 6 7 8 9
4. Array Initializers
In Java, you can initialize arrays during declaration or you can initialize (or change values) later in the
program as per your requirement.
The length of the array is determined by the number of values provided which is
separated by commas. In our example, the length of age array is 5.
Example Program: Write a Java Program to read elements into array and display them?
ArrayTest.java
import java.io.*;
class ArrayTest
{
public static void main(String args[]) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int a[]; //declaring array variable
int n, i; //size of the array
System.out.println("Enter the size of Array:");
n=Integer.parseInt(dis.readLine());
a=new int[n]; //allocating memory to array a and all the elements are set zero
//read the elements into array
System.out.println("Enter the elements into Array:");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(dis.readLine());
}
//displaying the elements
System.out.println("The elements of Array:");
for(i=0;i<n;i++)
{
System.out.print(a[i]+",");
}
}
}
Output:
C:/>javac ArrayTest.java
C:/>java ArrayTest
Enter the size of Array:
3
Enter the elements into Array:
15
36
78
The elements of Array:
15,36,78
Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look
and act like regular multidimensional arrays. However, as you will see, there are a couple of
subtle differences. To declare a multidimensional array variable, specify each additional index
using another set of square brackets. For example, the following declares a two dimensional
array variable called twoD.
int twoD[][] = new int[4][4];
This allocates a 4 by 4 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int.
Arrays of objects
Arrays are capable of storing objects also. For example, we can create an array of Strings which
is a reference type variable. However, using a String as a reference type to illustrate the concept
of array of objects isn't too appropriate due to the immutability of String objects
Syntax:
Class obj[]= new Class[array_length]
Example:
class ObjectArray{
public static void main(String args[]){
Account obj[] = new Account[2] ;//creates an array of two reference variables
obj[0] = new Account();//creates objects and assigns them to the reference variable array
obj[1] = new Account();//creates objects and assigns them to the reference variable array
obj[0].setData(1,2);
obj[1].setData(3,4);
System.out.println("For Array Element 0");
obj[0].showData();
System.out.println("For Array Element 1");
obj[1].showData();
}
}
class Account{
int a;
int b;
public void setData(int c,int d){
a=c;
b=d;
}
public void showData(){
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}
Output:
For Array Element 0
Value of a =1
Value of b =2
For Array Element 1
Value of a =3
Value of b =4
// Initializing array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
copying arrays
we can copy elements of array to another array as shown below
/ A Java program to demonstrate copying by one by one
// assigning elements of a[] to b[].
public class Test
{
public static void main(String[] args)
{
int a[] = {1, 8, 3};
Contents of b[]
2 8 3
In the previous method we had to iterate over the entire array to make a copy, we can do better by clone
method.
Object cloning means to create an exact copy of the original object.
If a class needs to support cloning, it must implement java.lang.Cloneable interface and override clone()
method from Object class. Syntax of the clone() method is :
protected Object clone() throws CloneNotSupportedException
If the object’s class doesn’t implement Cloneable interface then it throws an exception
‘CloneNotSupportedException’ .
// A Java program to demonstrate array copy using clone()
public class Test
{
public static void main(String[] args)
{
int a[] = {1, 8, 3};
Contents of b[]
283
Arrays.sort(arr);
Example :
Without predefined functions
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);//which takes input from keyboard
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
javac Ascending _Order.java
java Ascending _Order
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
Here the String class has a method length(), which is used to find the length of the string. This
length can be used to read all the arguments from the command line.
Inner Class:
Inner class is a class written within another' class. Inner class is hidden from other classes in its
outer class. The instance variables not accessed outside the class if they are specified with
'private' access specifier. This is how we provide the security to variables. Similarly, if we
specify private before outer class then it is illegal because it is not access by JVM. But we can
specify inner class as private thus it is useful to provide security for entire inner class. Once
private is used before the inner class, it is not available to other classes .This means an object to
inner class cannot be created in any other class.
}
Output
inside inner class Method
inside outerMethod
In the above code, we have two class Demo and Flavor1Demo. Here demo act as super class and
anonymous class acts as a subclass, both classes have a method show(). In anonymous class
show() method is overridden.
a) As implementer of the specified interface
class Flavor2Demo {
interface Hello {
void show();
}
Output:
i am in anonymous class
In above code we create an object of anonymous inner class but this anonymous inner class is an
implementer of the interface Hello. Any anonymous inner class can implement only one
interface at one time. It can either extend a class or implement interface at a time
Inheritance basics
Inheritance in Java is a mechanism in which one object acquires 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 fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
class Superclassname
Code;
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
Syntax:
{
Code;
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 a parent or superclass, and
the new class is called child or subclass.
Example
The following program creates a superclass called A and a subclass called B. Notice how the
keyword extends is used to create a subclass of A.
// Create a superclass.
class A
{
int i, j;
void showij() {
}
class SimpleInheritance
{
public static void main(String args[])
{ // subclass object creation, which acquires all the properties of the superclass B
b = new B();
/* The subclass has access to all public members of its superclass. */
b.i = 7;
b.j = 8;
b.k = 9;
System.out.println("Contents of b: ");
b.showij();
b.showk();
System.out.println("Sum of i, j and k in b:");
b.sum(); } }
Output: Contents of b:
i and j: 7 8 k: 9
Sum of i, j and k in b: i+j+k: 24
Forms of inheritances:
Single Inheritance:
In this type of inheritance we have single super class and a single sub class.
Super class
Sub class
In the above figure sub class is called as derived class which acquires the properties of super
class i.e. the base class
Multilevel:
In this type of inheritance child class will be inheriting a parent class and as
well as the derived class act as the parent class to other class. let us see the diagram
B
C
In the above example class C is derived class which acquires the properties of base class B , A in
which B acts as derived class which acquires the properties of class A.
Syntax:
class A
Statements;
class B extends A
Code
class C extends B
Code;
Hierarchical:
In this type of inheritance it has one base class and n number of derived classes.
Animal
Syntax:
Calss Animal
{
Code
}
Class Dog extends Animal
{
Code;
}
Class Cow extends Animal
{
Code;
}
Class Cat extends Animal
{
Code;
}
Multiple Inheritance :
It is the Inheritance which has many parent classes and one child here the child class tries to
acquire the properties of all the parent classes.
A B C
D
In the above figure class D is the child class which acquires the properties of the parent classes
like A,B and C.
Note:
Java does not support multiple inheritance because if two classes have same method with same
signature on calling the method the compiler cannot determine which class method is to be called
.But it can be achieved through interfaces.
Hybrid Inheritance:
B C
In the above figure class D is the derived class which acquires the properties of base classes like
B, C.And B,C Act as derived classes which acquires the properties of class A.
As java does not support multiple inheritances, the hybrid inheritance is also not supported as it
is the combination of Multiple and simple. So Hybrid can also achieve through interfaces only.
Member access and Inheritance
The most common use of inheritance and sub classing is for specialization. The child class that is
created new is specialized variety of parent class. Thus, this form always creates a subtype, and
the principle of substitutability is explicitly upheld.
For example:
Code;
Here PpfAccount is the derived class which acquires the methods of BankAccount like withdraw
(), balance () ect. The subclass always satisfies the specification of its super class; i.e. the
subclass is a subtype.
This the most common use of inheritance. Two important mechanisms have been specified by
java those are abstract and interface to make use of sub class specification. This is actually a
special case of sub classing for specialization, except that the subclasses are not refinements of
an existing type but rather realizations of an incomplete abstract specification. That is, the parent
class defines the operation, but has no implementation. It is only the child class that provides an
implementation. In such cases the parent class is sometimes known as an abstract specification
class.
An interface is used to describe only the necessary requirements, and no actual behavior is
inherited by a subclass that implements the behavior.
For example
Class B implements A
{
Class A extends B
A class can often inherit almost all of its desired functionality from a parent class, perhaps
changing only the names of the methods used to interface to the class, or modifying the
arguments. This may be true even if the new class and the parent class fail to share any
relationship as abstract concepts.
This type is mainly used for code reusability.
Sub classing for extension occurs when a child class only adds new behavior to the parent class,
and does not modify or alter any of the inherited attributes. An example of inheritance for
extension in the Java library is the class Properties, which inherits from class HashTable. A hash
table is a dictionary structure that dictionary stores a collection of key/value pairs, and allows the
user to retrieve the value associated with a given key.
{... }
{ ... }
}
As the functionality of the parent remains available and untouched, subclassing for extension
does not contravene the principle of substitutability and so such subclasses are always subtypes.
Subclassing for limitation occurs when the behavior of the subclass is smaller or more restrictive
than the behavior of the parent class. Like subclassing for extension, subclassing for limitation
occurs most frequently when a programmer is building on a base of existing classes that should
not, or cannot, be modified.
Suppose one wanted to create the class Set, in a fashion similar to the way the class Stack is
subclassed from Vector. However, you also wanted to ensure that only Set operations were used
on the set, and not vector operations. One way to accomplish this would be to override the
undesired methods, so that if they were executed they would generate an exception.
It is common for a new abstraction to be formed as a combination of features from two or more
abstractions. The properties are acquired by two or more parent classes is called multiple
inheritance. A teaching assistant, for example, may have characteristics of both a teacher and a
student, and can therefore logically behave as both.
As java does not support multiple inheritance it is archived by interfaces We saw this in the
example of the class Hole that both extended class Ball and implemented the interface for
PinBallTarget.
{ ...
It is also possible for classes to implement more than one interface, and thus be viewed as a
combination of the two categories
Java has many benefits the following are the benefits of java
Software Reusability:
Java main feature is cod reusability. The code once written can be used many times.
Many programmers spend much of their time rewriting code they have written many
times before -for example, to search for a pattern in a string or to insert a new element
into a table. With object-oriented techniques, these functions can be written once and
reused.
Increased Reliability:
Code that is executed frequently will tend to have fewer bugs then code that executed
infrequently. When the same components are used in two or more applications, the code
will be exercised more than code that is developed for a single application. Thus, bugs in
such code tend to be more quickly discovered, and latter applications gain the benefit of
using components are more error free.
Code Sharing:
Code sharing is another important feature of java. In which the cod written once by a
programmer can be shared by others i.e. sharing occurs when two or more classes
developed by a single programmer as part of a project inherit from a single parent class. F
Consistency of Interface
When two or more classes inherit from the same super class, we are assured that the
behavior they inherit will be the same in all cases. Thus, it is easier to guarantee that
interfaces to similar objects are in fact similar, and that the user is not presented with a
confusing collection of objects that are almost the same but behave, and are interacted
with, very differently.
Software Components
Inheritance helps us to develop reusable software components. The Java library provides
a rich collection of software components for use in the development of applications.
Rapid Prototyping
When a software system is constructed largely out of reusable components,
development time can be concentrated on understanding the new and unusual portion of
the system. Thus, software systems can be generated more quickly and easily, leading to
a style of programming known as rapid prototyping or exploratory programming.
Polymorphism and Frameworks: Polymorphism in programming languages permits the
programmer to generate high-level reusable components that can be tailored to different
applications by changes in their low-level parts. The Java AWT is an example of a large
software framework that relies on inheritance and substitutability for its operation
Information Hiding:
A programmer who reuses a software component needs only to understand the nature of
the component and its interface. It is not necessary for the programmer to have detailed
information concerning matters such as the techniques used to implement the component.
Thus, the interconnectedness between software systems is reduced. We earlier identified
the interconnected nature of conventional software as being one of the principle causes of
software complexity
C:/>javac Hirerachy.java
C:/>java Hirerachy
A reference variable of a superclass can be assigned a reference to any subclass derived from that
superclass. You will find this aspect of inheritance quite useful in a variety of situations. when a
reference to a subclass object is assigned to a superclass reference variable, you will have access only to
those parts of the object defined by the superclass.
For example,
class Box
double width,height,depth;
}
double weight;
{ width=x;
height=y;
depth=z;
weight=a;
void volume()
}}
//main class
class BoxDemo
bw=new Boxweight(2,3,4,5);
bw.volume();
// b has been created with its own data, in which weight is not a member
// here it raises error, super class does not contain the volume() method
}}
super(arg_list);
class Teacher
Teacher()
System.out.println(“He is aTeacher”);
void college()
//sub calss
Student()
super();
System.out.println(“He is Student”);
void college()
class Demo2
Output:
He is Cse Student
He belongs to NRIIT
C:/>javac UseSuper.java
C:/>java UseSuper
i in superclass:1
i in subclass:2
Calling Constructor
The super keyword can also be used to invoke the parent class constructor.
Syntax:
super()
class Animal{
Animal()
{
System.out.println("animal is created");}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class Test{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
C:/>javac Test.java
C:/>java Test
animal is created
dog is created
Using final with Inheritance
The keyword final has three uses. First, it can be used to create the equivalent of a named
constant. The second is used to prevent the method overriding. The third, is used to prevent the
inheritance.
1. Creating the constant using final keyword
The final keyword can be used to create constants. The general form of the statement is as
follow:
final type variable_name=value;
where type can be any primitive data type, and variable_name can be any valid identifier. For
example,
final int speed=120;
2. 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 overridden, specify
final as a modifier at the start of its declaration. Methods declared as final cannot be overridden.
The following fragment illustrates final:
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a
compile-time error will result. Methods declared as final can sometimes provide a performance
enhancement: The compiler is free to inline calls to them because it “knows” they will not be
overridden by a subclass. When a small final method is called, often the Java compiler can copy
the bytecode for the subroutine directly in line with the compiled code of
the calling method, thus eliminating the costly overhead associated with a method call.
Inlining is only an option with final methods. Normally, Java resolves calls to methods
dynamically, at run time. This is called late binding. However, since final methods cannot be
overridden, a call to one can be resolved at compile time. This is called early binding.
3. Using final to Prevent Inheritance
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 subclasses to provide complete
implementations.
Here is an example of a final class:
final class A
{
// ...
}
// The following class is illegal.
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.
Advantages of inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code exists
in two related classes, the hierarchy can usually be refactored to move the common code up to
a mutual superclass. This also tends to result in a better organization of code and smaller,
simpler compilation units.
Inheritance can also make application code more flexible to change because classes that inherit
from a common superclass can be used interchangeably. If the return type of a method is
superclass
Reusability - facility to use public methods of base class without rewriting the same.
Extensibility - extending the base class logic as per business logic of the derived class.
Data hiding - base class can decide to keep some data private so that it cannot be altered by
the derived class
Overriding -With inheritance, we will be able to override the methods of the base class so
that meaningful implementation of the base class method can be designed in the derived class.
Polymorphism:
It is a Greek word in which ploy means many, morphism means forms.In which it ability to show
one thing in many forms. For example, we use mobile for communication. The communication
mode we choose could be anything. It can be a call, a text message, a picture message, mail, etc.
So, the goal is common that is communication, but their approach is different. This is
called Polymorphism
compile-time polymorphism
runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding. f you
overload a static method in Java, it is the example of compile time polymorphism
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved
at run time, rather than compile time. Dynamic method dispatch is important because this is how
Java implements run-time polymorphism.
Let’s begin by restating an important principle: a superclass reference variable can refer to a
subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here is
how. When an overridden method is called through a superclass reference, Java determines
which version of that method to execute based upon the type of the object being referred to at the
time the call occurs. Thus, this determination is made at run time.
Here is an example that illustrates dynamic method dispatch:
// Dynamic Method Dispatch or run-time polymorphism
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A’s callme method
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden. Consider the following example:
class A
{
void disp()
{
System.out.println("This is the class A method");
}
}
// extending the superclass properties
class B extends A
{
void disp()
{
System.out.println("This is the class B method");
}
}
// main class
class OverRide
{
public static void main(String args[])
{
B b=new B();
b.disp(); // super class method is hidden, subclass method is invoked
}
}
output:
This is the class B method
Inside B’s callme method
Inside C’s callme method
Overriding methods must have the same name, parameter list, and same return type. i.e.,
they must have the exact signature of the method we are going to override, including
return type.
The overriding method cannot be less visible than the method it overrides. i.e., a public
method cannot be override to private
The overriding method may not throw any exceptions that may not be thrown by the
overridden method.
abstract classes
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. There can be no objects of an abstract class. That is, an abstract class cannot
be directly instantiated with the new operator. Such objects would be useless, because an abstract
class is not fully defined.
Object class is root class for all other classes. This means that a reference variable of type
Object can refer to an object of any other class
Object defines the following methods, which means that they are available in every object
methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override
the others. These methods are described elsewhere in this book. However, notice two methods
now: equals( ) and toString( ). The equals( ) method compares the contents of two objects. It
returns true if the objects are equivalent and false otherwise
In this unit we gained knowledge about constructor and types of constructors ,and how the
memory was deallocate in java ,we also learnt that arrays are very useful for ,a programmer to
handle a group elements easily, In Java, we got Static methods,instance methods ,the values can
also be passed dynamically by using command line arguments.When the programmer wants to
restrict the access of entire code of a class, he creates an inner class as a private class. so we can
access the inner class is through its outer class only and authentication mechanism is
implemented in the outer class.
Review Questions
-------------------------
1. Write about multidimensional arrays in java.
2. What is the importance of constructor? Write a java program to perform constructor
overloading.
3. Write about command line arguments.
4. What is method overriding? Illustrate the concepts of method overriding and constructor
overriding.
5. With suitable program segments describe the usage of ‘super’ keyword.
6. What is a nested class? Differentiate between static nested classes and non-static nested
classes.
7. Distinguish between abstract class and concrete class.
8. Explain the various access specifiers are used in java
9. Explain multilevel inheritance with the help of abstract class in your program
10. What is meant by dynamic method dispatch? Explain with a program.
11. What is inheritance? Explain different forms of inheritance with suitable program segments
and real world example classes
12. Explain the use of ‘this’ keyword.
13. Write about garbage collection in Java.
b) Throws exception
c) compile time error
d) Runs successfully
3. What is false about constructor?
a) Constructors cannot be synchronized in Java
b) Java does not provide default copy constructor
c) Constructor can be overloaded
d) “this” and “super” can be used in a constructor
4. What is true about Class.getInstance()?
a) Class.getInstance calls the constructor
b) Class.getInstance is same as new operator
c) Class.getInstance needs to have matching
constructor
d) Class.getInstance creates object if class does not
have
any constructor
5. What is true about constructor?
a) It can contain return type
int y;
void add(int a)
{
x = a + 1;
}
void add(int a, int b)
{
x = a + 2;
}
}
class Overload_methods
{
public static void main(String args[])
{
overload obj = new overload();
int a = 0;
obj.add(6);
System.out.println(obj.x);
}
}
a) 5
b) 6
c) 7
d) 8
12.Which of the following is a garbage collection
technique?
a) Cleanup model
b) Mark and sweep model
c) Space management model
d) Sweep model
13.Garbage Collection can be controlled by a
program?
a) True
b) False
14. What is the return type of Constructors?
a) int
b) float
c) void
d) none of the mentioned
15:Which keyword is used by the method to refer to
the object that invoked it?
a) import
b) catch
c) abstract
d) this
16.Which of the following statements are incorrect?
a) default constructor is called at the time of object
declaration
b) Constructor can be parameterized
c) finalize() method is called when a object goes out
of scope and is no longer needed
d) finalize() method must be declared protected
17.Which one of the following is not an access
modifier?
a) Public
b) Private
c) Protected
d) Void
18.Which of these keywords is used to prevent
content of a variable from being modified?
a) final
b) last
c) constant
d) static
19.Which of these cannot be declared static?
a) class
b) object
c) variable
d) method
20.Which of these methods must be made static?
a) main()
b) delete()
c) run()
d) finalize()
21.what is the use of this keyword?
a)this can be used to refer current class instance
variable.
b)this can be used to invoke current class method
(implicitly)
c)this can be passed as an argument in the method
call.
d)all of the above.
22.Arrays in Java are implemented as?
a) class
b) object
c) variable
d) none of the mentioned
23.What is the output of this program?
class Output
{
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5};
for ( int i = 0; i < arr.length - 2; ++i)
System.out.println(arr[i] + " ");
}
}
a) 1 2
b) 1 2 3
c) 1 2 3 4
d) 1 2 3 4 5
24.Which of this method is given parameter via
command line arguments?
a) main()
b) recursive() method
c) Any method
d) System defined methods
{
System.out.print("args[0]");
}
}
a) java
b) Output
c) This
d) is
28.how many types of nested classes in java?
a)2
b)4
c)1
d)5
29.Can we access non-static members of outer
class inside a static nested class?
a)yes
b)no
c)none
d)a&b
30.How to Create Anonymous Class in Java?
a)Using Class
b) Using Interface
c)both class and interface
d)none
31.Output of follwoing Java program
class Main {
public static void main(String args[]){
final int i;
i = 20;
System.out.println(i);
}
}
a)20
b)Compiler Error
c)0
d)Garbage value
32. Which of these class is superclass of every class
in Java?
a) String class
b) Object class
c) Abstract class
d) ArrayList class
33.What is the output of this program?
abstract class A
{
int i;
abstract void display();
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class Abstract_demo
{
public static void main(String args[])
{
B obj = new B();
obj.j=2;
obj.display();
}
}
a) 0
b) 2
c) Runtime Error
d) Compilation Error
34. Which of these keywords can be used to prevent
inheritance of a class?
a) super
b) constant
c) class
d) final
35. Which of this keyword can be used in a subclass
to call the constructor of superclass?
a) super
b) this
c) extent
d) extends
36.What is the process of defining a method in a
subclass having same name & type signature as a
method in its superclass?
a) Method overloading
b) Method overriding
c) Method hiding
d) None of the mentioned
37.Which of these is supported by method overriding
in Java?
a) Abstraction
b) Encapsulation
c) Polymorphism
d) None of the mentioned
38.What is the output of this program?
class A
{
int i;
public void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
a) 1
b) 2
c) 3
d) 4
39. Which of these keywords are used to define an
abstract class?
a) abst
b) abstract
c) Abstract
d) abstract class
40. Which of these is not a correct statement?
a) Every class containing abstract method must be
declared abstract
b) Abstract class defines only the structure of the
class not its implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited
41. Which of these packages contains abstract
keyword?
a) java.lang
b) java.util
c) java.io
d) java.system
42. What is the output of this program?
class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
43.What is the return type of a method that does not
return any value?
a) int
b) float
c) void
d) double
44.Which of this statement is incorrect?
a) All object of a class are allotted memory for the
all the variables defined in the class
b) If a function is defined public it can be accessed
by object of other class by inheritation
c) main() method must be made public
d) All object of a class are allotted memory for the
methods defined in the class
45.Which of these is correct way of inheriting class
A by class B?
a) class B + class A {}
c) Protected methods
d) Private methods
49.Which of the following is used for implementing
inheritance through an interface?
a) inherited
b) using
c) extends
d) implements
50.What is the output of this program?
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class inheritance_demo
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 0
b) 1
c) 2
d) Compilation Error
51.What do you call the languages that support
classes but not polymorphism?
a) Class based language
b) Procedure Oriented language
c) Object-based language
d) If classes are supported, polymorphism will
always be supported
52.Which among the following is the language which
supports classes but not polymorphism?
a) SmallTalk
b) Java
c) C++
d) Ada
53. Which type of function among the following
shows polymorphism?
a) Inline function
b) Virtual function
c) Undefined functions
d) Class member functions
54.. Which among the following cant be used for
polymorphism?
a) Static member functions
b) Member functions overloading
c) Predefined operator overloading
d) Constructor overloading
55. Which among the following can show
polymorphism?
a) Overloading ||
b) Overloading +=
c) Overloading <<
d) Overloading &&
56. How many types of inheritance are possible in
C++?
a) 2
b) 3
c) 4
d) 5
57. Which type of inheritance results in diamond
problem?
a) Single level
b) Hybrid
c) Hierarchical
d) Multilevel
58.Which type of inheritance cannot involve private
inheritance?
a) Single level
b) Multiple
c) Hybrid
d) All types can have private inheritance
59. Diamond problem includes ____________________
hybrid inheritance
a) Hierarchical and Multiple
b) Hierarchical and Hierarchical
c) Multiple and Multilevel
d) Single, Hierarchical and Multiple
60. If hybrid inheritance is used, it mostly shows
_______________ feature of OOP.
a) Flexibility
b) Reusability
c) Efficiency
d) Code readability
answers: