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

Unit - I

The document provides an introduction to Java programming, covering object-oriented programming concepts, Java features, and the Java environment. It details the compilation process, Java syntax, data types, operators, and command line arguments, along with examples of Java code. Additionally, it explains Java's unique characteristics such as platform independence, security, and automatic memory management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit - I

The document provides an introduction to Java programming, covering object-oriented programming concepts, Java features, and the Java environment. It details the compilation process, Java syntax, data types, operators, and command line arguments, along with examples of Java code. Additionally, it explains Java's unique characteristics such as platform independence, security, and automatic memory management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

PROGRAMMING IN JAVA

UNIT I : INTRODUCTION TO OOP AND JAVA FUNDAMENTALS 9

Object Oriented Programming - Abstraction – objects and classes - Encapsulation-


Inheritance - Polymorphism- Characteristics of Java – The Java Environment -
Java Source File - Compilation. Fundamental Programming Structures in Java –
Defining classes in Java – constructors, methods - Access specifiers - static
members - Comments, Data Types, Variables, Operators, Control Flow, Arrays ,
Packages - JavaDoc comments.

Java Features

Java is a high level language looks much similar to C, C++ but it offers many
unique features that are not available in most of modern programming language.
Java language has the following features.

• Compiled and Interpreted


• Platform Independence
• Object Oriented
• Robust
• Security
• Automatic Memory Management
• Dynamic Binding
• High Performance
• Multithreaded
• Some dangerous features in C/C++ eliminated

Compiled and Interpreted

Java compiler converts the source code into intermediate byte code instructions
.Java Interpreter converts these bytes codes into machine executable statements.
Thus we can say java is both compiled and interpreted language. The two steps of
compilation and interpretation allow for extensive code checking and improved
security

Platform Independence

1
Java programs are capable of running on all platforms hence java programs
possess Write-Once-Run-Anywhere feature

Object Oriented
Java is purely an object oriented language. In Java no coding outside of class
definitions is allowed, including the main() function. Java supports an extensive
class library available in the core language packages.
Robust
Java is a robust language. It provides the following facilities to ensure reliable
code
• Built in Exception Handling
• Strong type checking both at compile and runtime.
• Local variables must be initialized
Security
Java is a highly secured language. Java programs will run only within the Java
Virtual Machine (JVM) sandbox thus threats from malicious programs is
minimized. Java does not support pointers hence direct memory access is not
allowed. Java supports a built in security manager that determines what resources
a class can access such as reading and writing to the local disk.
Automatic Memory Management

Java supports automatic memory management. Java Virtual machine (JVM)


performs garbage collection automatically to claim the memory occupied by
unused objects.

Dynamic Binding

Java is a dynamic language. The linking of data and methods occurs only at run
time. In java new classes can be loaded even when the program is on execution.
High Performance
Interpretation of bytecodes slowed performance in early versions, but advanced
virtual machines with adaptive and just-in-time compilation and other techniques
now typically provide performance up to 50% to 100% the speed of C++
programs.
Multithreaded
In java it possible to write programs to handle multiple tasks simultaneously. To
write such programs you have to create light weight processes called “Threads” in
java. The threads thus created can be executed simultaneously. Multithreaded
programs are useful when you write programs for networking and multimedia.

2
Java Environment

Java Virtual Machine


You have learnt that java is a platform independent and architectural neutral
language. These features are provided by the java run time environment called
Java Virtual Machine (JVM).When a java program is compiled it will not produce a
machine code instead it produces an intermediate byte code for the JVM. When
you run the java program the byte code produced for the JVM will be interpreted
by the java run time interpreter. This interpreter converts the byte code to the
executable machine code for the machine that runs the java program. The
process of compilation and execution is shown below.
JAVA PROGRAM

JAVA COMPILER

BYTE CODE Compil

BYTE CODE

JAVA INTERPRETOR

MACHINE CODE

Execution Process

The byte code produced by the java compiler for the JVM is common to all
platforms hence byte code is platform independent.

Writing Java Source Code

Writing java source code is similar to writing a source code in C++ but with some
variations. Writing Java source code is dealt in detail in subsequent chapters. Now
let’s start our discussion by writing a simple java program.The following is a
simple java program. The source code is written in the file named “Welcome.java”

3
class Welcome
{
public static void main(String args[])
{
// The following line is used to display a line of text
System.out.println(“Welcome to Java world “);
}
}

To compile this program you have to use the “javac” compiler. The syntax to
compile is

javac filename.java

To compile this program you have to type

javac welcome.java in the command prompt. This will create a class called
“welcome.class” which contains the byte code representation of the program.

To run the java program you have to use the java interpretor. The syntax to run
is

java classname

• The First line of this program has the class declaration, as mentioned earlier
every code written in java should be kept inside a class definition.
• The third line declares the main() method in java. The main() method in
java should be declared public and static .Usually the return type of the
main method is void.
• In java main() method should be declared public because main() method
should be made accessible to all other classes
• main() method is declared static because the main() method belongs to the
class not to a specific object
• System.out.println() is a statement used to display some text to the user. It
is similar to cout statement in C++.

4
Example 1:

The code listed below performs addition of two integer numbers.

class sum
{
public static void main(String args[])
{
int i=10,j=25;
k=i+j;
System.out.println(“THE SUM IS “+k);
}
}

In this example you have declared two integer variables i and j .The + operator
used in the System.out.println() is concatenation operator.

Introduction

Java is an object oriented language developed by Sun Microsystems. Around 1990


James Gosling, Bill Joy and others at Sun Microsystems began developing a
language called Oak. Oak language was primarily developed to control
microprocessors embedded in consumer items like PDA’s for this language should
be a platform independent, reliable and compact language.

But however due to the sudden explosion of Internet and similar technologies,
Sun Microsystems changed their project objectives and renamed the Oak
language into Java. In 1994 the project team developed a web browser called
“HotJava” capable of locating and running applets, a java program that can run on
a web browser.

The earlier versions of java were not so powerful but now Java has became a
common language to develop applications like on line web stores, transactions
processing, database interfaces etc., java has also become quite common on
small platforms such as cell phones and PDAs. Java is now used in several
hundred cell phone models. This chapter explores the various fundamental
programming concepts of Java.

5
Java Tokens

As mentioned in chapter 1 tokens are the basic lexical elements of any


programming language In Java every statement is made up of smallest individual
elements called tokens. Tokens in java include the following

• Keywords
• Identifiers
• Literals
• Operators

Keywords

The list is of keywords available in java are given below. Every keyword will
perform a specific operation in java. As mentioned in chapter 1 keywords cannot
be redefined by a programmer; further keywords cannot be used as identifier
name.

Abstract continue for new switch

Assert default goto package synchronized

Boolean do if private this

Break double implements protected throw

Byte else import public throws

Case enum instanceof return transient

Catch extends int short try

Char final interface static void

class finally long strictfp volatile

const float native super while

• In Java the keyword const, goto are not used


• The keyword assert is added in version 1.4
• The keyword enum is added in version 5.0

6
Identifiers

Every named program component—class, package, function or variable must have


a legal identifier (or name). An identifier in java has the following rules

• An identifier can contain alphanumeric characters, but it should begin with


an alphabet.
• Identifiers are case sensitive(i.e. upper and lower cases are different)
• Underscore and dollor sign are two special character allowed.

The following are legal identifiers


• Find_3
• Message
• abc$
• A23C

The following are the invalid identifiers


• 33pages
• bob@gmail

Literals

A literal is a program element that represents an exact (fixed) value of a certain


type. Java language supports the following type of literals

• Integer Literals (Ex. 123)


• Floating point Literals (Ex. 88.223)
• Character Literals (Ex. ‘.’ , ‘a’ , ‘\n’)
• String Literals (Ex. “Hello World”)
• Boolean Literals (Ex. True,false)

Operators

Java is a language that is rich in operators. The list of operators supported in java
is given below.

Simple Assignment Operator


= Simple assignment operator

Arithmetic Operators
+ Additive operator (also used for String concatenation)

7
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

Unary Operators
+ Unary plus operator; indicates positive value (numbers are positive
without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical compliment operator; inverts the value of a boolean

Equality and Relational Operators


== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)

Type Comparison Operator


instanceof Compares an object to a specified type

Bitwise and Bit Shift Operators


~ Unary bitwise complement
<< Signed left shift
>> Signed right sift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

The operator precedence table is given below.

Operator Precedence

Operators Precedence

8
postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative */%

additive +-

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ?:

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Expressions

Java is an expression based language. In Java expressions are used to implement


some computation. Expressions in java can be either a simple expression or a
complex expression. A simple expression may be a value assigned to variable
complicated expression is composed of an operator applied to one or more
operands, all of which are also expressions. In Java expressions takes the general
form

9
variable=expression;

For Example

x=a+b; //Simple expression


y=a*(b+c)/(m+n)*f //Complex expression
a+=b //Similar to a=a+b.

Data Types

Java supports the following list of data types. They are

• boolean

1-bit. May take on the values true and false only.


true and false are defined constants of the language and are not the same
as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other
numeric value. Booleans may not be cast into any other type of variable nor
may any other variable be cast into a boolean.

• byte

1 signed byte (two's complement). Covers values from -128 to 127.

• short

2 bytes, signed (two's complement), -32,768 to 32,767

• int

4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like


all numeric types ints may be cast into other numeric types (byte, short,
long, float, double). When lossy casts are done (e.g. int to byte) the
conversion is done modulo the length of the smaller type.

• long

8 bytes signed (two's complement). Ranges from -


9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

• float

4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to


3.40282346638528860e+38 (positive or negative).
Like all numeric types floats may be cast into other numeric types (byte,
short, long, int, double). When lossy casts to integer types are done (e.g.

10
float to short) the fractional part is truncated and the conversion is done
modulo the length of the smaller type.

• double
8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to
1.79769313486231570e+308d (positive or negative).

• char

2 bytes, unsigned, Unicode, 0 to 65,535

Variables Declaration

The syntax of declaring a variable in java is similar to that of C, C++. Variables


are the names of storage location. The following are the examples of variable
declaration
• int i; //declares a integer variable i
• int i,j //declares two integer variables i and j
• int i=3,j=7;//declares and initialize the values i and j

Constants

Constants refer to values that do not change during the execution of the program.
Examples for constants are

1998 Integer constant


25.789 Floating point constant
“Hello World” String constant
‘a’ Character constant

Apart from these types of constants java also supports backslash character
constants

BACKSLASH CONSTANT PURPOSE

\b Backspace

\f Form feed

\n New Line

\r Carriage return

11
\t Horizontal tab

\\ Backslash

Command Line Arguments


In Java it is possible to provide input to a program as command line arguments.
The String args[] argument in the main method is used to supply command line
arguments to the program. Java programs accept only strings as command line
arguments. However you can convert these arguments into the desired data types
using the wrapper classes.

Note:

Java provides classes to represent simple data types like int, float etc., as class. That is
these classes warp the simple types to class types. These classes are called Wrapper
classes. Every simple data type in Java will have its corresponding wrapper class.

Thus using wrapper classes you can convert the string to the corresponding
simpler type. The signature for the Integer wrapper class is

• static int parseInt(String s)

For example

• Integer.parseInt(“10”)

will convert the string “10” to integer 10. The Integer wrapper class has a static
method called parseInt to perform this job. Similarly the signature of the Double
wrapper class is

• static int parseDouble(String s)

For example

• Double.parseDouble(153.18)

12
will convert the string “153.18” to double 153.18. The Double wrapper class has a
static method called parseDouble to perform this job. Similar methods are
available for all the simple types.

The command line arguments passed to program are stored in the String array
args[] . The first element is referenced as args[0] , the next element as args[1]
and so on.

Command line arguments are supplied to the program when you run the program.
For example when you run the program named “hello.java”

C:\jdk1.5.0\bin> java hello 123 abc 12.88

• args[0] contains 123


• args[1] contains abc
• args[2] contains 12.88

Example 7:

The following example accepts two command line arguments and computes the
sum of two numbers.

class sum
{
public static void main(String args[])
{
double i,j,s;
i=Double.parseDouble(args[0]);
j=Double.parseDouble(args[1]);
s=i+j;
System.out.println("The sum is "+s);
}}

Output of the Program

13
Example 8:

The following example accepts a number ‘n’ as command line argument and
generates ‘n’ Fibonacci numbers.

class fib
{
public static void main(String args[])
{
int n;
int a=0,b=1,c;
n=Integer.parseInt(args[0]);
for(int i=0;i<n;i++)
{
c=a+b;
System.out.println("The next number is "+c);
a=b;
b=c;

}
}
}

Output of the Program

14
Note:

The length of the command line arguments can be found using the variable length. For
example args.length

Example 9:

The following example prints number of command line arguments passed.

class count
{
public static void main(String args[])
{
int n;
n=args.length;
System.out.println("The count is "+n);
}
}

15
Output of the Program

c:\jdk1.5.0\bin> javac count.java

c:\jdk1.5.0\bin> java count 1 2 3

The count is 3

Objects

Objects are the run time instance of a class. Classes describe objects. Many
objects can be instantiated from one class. Objects of different classes can be
created, used, and destroyed in the course of executing a program.

Objects in java are created using the “new” operator. For example to create an
object for the GUI class we follow the given syntax.

GUI obj=new GUI(); //declare and instantiate

OR

GUI obj; //declare


Obj=new GUI(); //instantiate

Adding Variables to Classes

A class can contain variables. The variables added to the class are called instance
variables. Variables are declared in the java classes as mentioned below.

class product
{
int prod_id;
String prod_name;
double price;
}

Adding Methods to Classes

Methods in Java determine the messages an object can receive. Methods in Java
can be created only as part of a class. A method can be called only for an object,
You call a method for an object by naming the object followed by a period (dot),
followed by the name of the method and its argument list, for example:

16
objectName.methodName(arg1, arg2, arg3)

The signature of a method comprises the method name and parameter list. The
combined name and parameter list for each method in a class must be unique.
The Syntax to declare a method in java is

[modifiers] return_type <method_name> (parameter_list) [throws_clause ]

//method body

• Return Type: The return type is either a valid Java type (primitive or class)
or void if no value is returned. If the method declares a return type, every
exit path out of the method must have a return statement.
• Method Name: The method name must be a valid Java identifier
• Parameter List: The parentheses following the method name contain zero
or more type/identifier pairs that make up the parameter list. Each
parameter is separated by a comma. Also, there can be zero parameters.

There are a number of optional modifiers that you can use when declaring a
method. They are listed in the following table:

Modifier Description

Can be one of the values: public, protected, or private.


Visibility
Determines what classes can invoke the method.

The method can be invoked on the class instead of an


static
instance of the class.

The method is not implemented. The class must be


abstract extended and the method must be implemented in the
subclass.

final The method cannot be overridden in a subclass.

native The method is implemented in another language.

17
The method requires that a monitor (lock) be obtained
synchronized
by calling code before the method is executed.

throws A list of exceptions thrown from this method.

Now, consider the product class created previously, we can add two methods
getDetails() and displayDetails() to the class.

class product
{

int prod_id;
double price;
void getDetails(int a,String b,double c)
{
prod_id=a;
price=c;
}
void displayDetails()
{
System.out.println(“Product id is “+prod_id);
System.out.println(“Price is “+price);
}
}

Example 1:

The following java program performs the basic calculator functions.

class Calculator

int n1,n2,res;

void setData(int x1,int x2)

n1=x1;

n2=x2;

18
void add()

res=n1+n2;

System.out.println(“The Sum is : “+res);

void sub()

res=n1-n2;

System.out.println(“The Difference is : “+res);

int mul()

res=n1*n2;

return res;

double div()

return n1/n2;

class Mainprg

public static void main(String args[])

Calculator cal=new Calculator();

cal.setData(20,10);

19
cal.add();

cal.sub();

int y=cal.mul();

System.out.println(“The Product is : “+y);

double d=cal.div();

System.out.println(“The divided value is :“+d);

The Output of the Program is

The Sum is : 30

The Difference is : 10

The Product is : 200

The divided value is : 2.0

Constructors

Constructors are special type of methods that are invoked when we create objects
for the classes. Constructers will have the same name as that of the class.
Constructors and methods differ in two important aspects of the signatures. They
are

• Modifiers
• Return types

Like methods, constructors can have any of the access modifiers: public,
protected, private, or none (often called friendly). However constructors cannot be
made abstract, final, native, static, or synchronized.

20
Methods can have any valid return type, or no return type, in which case the
return type is given as void. Constructors cannot take any return type, even void.

Example 2:

The Calculator class created in example 1 is modified, the setData() method is


replaced with a constructer.

class Calculator

int n1,n2,res;

Calculator (int x1,int x2) //Constructor

n1=x1;

n2=x2;

void add()

res=n1+n2;

System.out.println(“The Sum is : “+res);

void sub()

res=n1-n2;

System.out.println(“The Difference is : “+res);

int mul()

21
res=n1*n2;

return res;

double div()

return n1/n2;

class Mainprg

public static void main(String args[])

Calculator cal=new Calculator(20,10); //Calls the constructer


cal.add();

cal.sub();

int y=cal.mul();

System.out.println(“The Product is : “+y);

double d=cal.div();

System.out.println(“The divided value is :“+d);

Output of the Program

The Sum is : 30

The Difference is : 10

The Product is : 200

The divided value is : 2.0

22
Access Specifiers

An access specifier in java determines which data member, which method can be
used by other classes. Java supports three access specifiers and a default access
specifier. Access specifiers are also known as access modifiers. The three access
specifiers supported in Java are

• The private access specifier


• The public access specifier
• The protected access specifier

Only objects of the same class can have access rights to a method or data
member declared as private. A method or a data member can be declared as
private by prefixing it with the keyword private. For example

• private int sum; // private variable


• private void method1() //private method declaration
{

//method body

A data member or a method declared as public can be accessed by all classes and
their objects. To declare a data member or a method as public prefix the
declaration with the keyword public. For example

• public double area //public variable


• public void calculate() //public method
{

//method body

23
Data members, methods that are declared protected are accessible by that class
and the inherited subclasses. Methods and variables can be declared as protected
by prefixing the declaration with the protected keyword.

• protected String msg; //protected variable


• protected int search() //protected method
{

//method body

Default Access

If none of the above mentioned access specifiers are specified to a method or a


variable, then the scope is considered to be friendly, this is the default access
scheme in Java. A class, method, variable with a friendly scope is accessible to all
the classes of the package. packages are discussed in chapter 15.

Method Overloading

Overloading is one of the important polymorphic features of the Object Oriented


System. Like C++ functions we can also overload Java methods. In Java two or
more methods can share the same name as long as either the type of their
arguments differs or the number of their arguments differs - or both. When two or
more methods share the same name, they are said overloaded.

Example 3:

The coding listed below overloads the method sum()

class numbers

24
void sum(int x,int y)

int z=x+y;

System.out.println(“Sum of addition of two numbers : “+z);

void sum(int x,int y,int z)

int r=x+y+z;

System.out.println(“Sum of addition of three numbers : “+z);

class test

public static void main(String args[])

test t=new test();

t.sum(10,20); //Call the method sum with two parameters

t.sum(10,20,30); //Call the method sum with three parameters

25
Output of the Program

Sum of addition of two numbers: 30

Sum of addition of three numbers: 60

In this program the method sum is overloaded. From the main method when we
call the sum method the corresponding the overloaded version of the sum method
is called.

Constructer Overloading

In Java, similar to the concept of method overloading we have constructer


overloading. In constructer overloading we have multiple constructers that differ
either in type of their arguments or the number of their arguments or both. The
constructer that takes no parameter is called default constructer. Below is the
example of constructer overloading.

Example 4:

The program given below makes use of constructer overloading concept.

class dimension

int x1,y1;

dimension() //default constructor

x1=0;

y1=0;

26
}

dimension(int a)

x1=a;

y1=0;

dimension(int a,int b)

x1=a;

y1=b;

void display()

System.out.println(“ x1 is :“+x1);

System.out.println(“ y1 is :“+y1);

class Mainprg

public static void main(String args[])

dimension d1=new dimension(10,50); //Calls constructer with two


parameter

dimension d2=new dimension(10); //Calls constructer with one


parameter

dimension d3=new dimension(); //Calls default constructer

d1.display();

27
d2.display();

d3.display();

Output of the Program

x1 is : 10

y1 is : 50

x1 is : 10

y1 is : 0

x1 is : 0
Static Data Members
y1 is : 0
Each object of a given class has its own copy of all the data defined by the class.
Sometimes it is desirable for all the objects of a particular class to share data. In
Java this can be achieved by defining the corresponding class members as static
using the keyword static. Since static variables are common all the instances of
the class, static variables can also be called as class variables.

• for a static data member there will be only one copy of the class member
shared by all objects of the class.
• A static data member is like a global variable, but has class-level scope.

To declare a variable as static we have to simply prefix the variable declaration

with the keyword static. For example

static int x;

Static Methods

Like static variables , static methods are called without the object. The differences
between a static methods and non-static methods are as follows.

28
• A static method can access only static data and can call only other static
methods. A non-static member function can access all of the above
including the static data member.
• A static method can be called, even when a class is not instantiated, a non-
static member function can be called only after instantiating the class as an
object.
• A static method cannot have access to the 'this' keyword.
• A static method cannot have access to the ‘super’ keyword.

Example 5:

This program makes use of static data members and methods

class test

static int increment(int k)

k++;

return k;

static int decrement(int j)

j--;

return j;

class static_test

public static void main(String args[])

29
{

int a=static_test.increment(10);

System.out.println(“Incremented Value is : “+a);

int b=static_test.decrement(20);

System.out.println(“Decremented Value is : “+b);

Output of the Program

Incremented Value is : 11

Decremented Value is : 19

In Java class libraries many static methods are found. For example in java.lang
package, we have a class called “Math” all the methods declared in the Math class
are static.

Example 6:

This program makes use of some static methods available in Math class.

class Math_test

public static void main(String args[])

System.out.println(“Sin 30 is “+Math.sin(30));

System.out.println(“Square root of 25 is “+Math.sqrt(25));

System.out.println(“Absolute value for -15 is “+Math.abs(-15));

30
System.out.println(“Log value for 88.87 is “+Math.log(88.87));

System.out.println(“3 Power 5 is ”+ Math.pow(3,5));

Output of the Program

Sin 30 is -0.9880316240928618

Square root of 25 is 5.0

Absolute value for -15 is 15

Log value for 88.87 is 4.487174627750384


Inheritance
3 Power 5 is 243.0
Inheritance is a feature by which new classes are derived from the existing
classes. Inheritance allows re-using code without having to rewrite from scratch.
Inheritance is a compile-time mechanism in Java that allows you to extend a class
(called the base class or superclass) with another class (called the derived class or
subclass). In Java, inheritance is used for two purposes:

• Class inheritance - create a new class as an extension of another class,


primarily for the purpose of code reuse. That is, the derived class inherits
the public methods and public data of the base class. Java only allows a
class to have one immediate base class, i.e., single class inheritance
• Interface inheritance – Interface inheritance is used to achieve multiple
inheritance. It is discussed in detail in chapter 14.

The Syntax for class inheritance is given below

[public ] class <classname> extends ParentClass

//variables and methods declaration

31
In keyword extends is used to implement inheritance in Java. In Java the
following forms of class inheritance is supported.

• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance.

Example 7:

The program listed below is a single inheritance program.

class rectangle

int l;

int b;

rectangle(int x,int y)

l=x;

b=y;

void rect_area()

System.out.println(“Area of Rectangle is “ + l*b);

32
class cube extends rectangle

int h;

cube(int x,int y,int z)

super(x,y);

h=z;

void cube_volume()

System.out.println(“Volume of the Cube is “ + l*b*h);

class Mainprg

public static void main(String args[])

cube c=new cube(10,20,30);

c.rect_area();

c.cube_area();

Output of the Program

Area of Rectangle is 200

33
Volume of the Cube is 6000
Super Keyword

Java uses a unique keyword called “super” to call the super class constructers. In
the previous example we have used super keyword to pass parameters to the
super class constructer from the sub class constructer. The following is the syntax
of super keyword

super() (or)

super(parameter list)

With super(), the superclass no-argument constructor is called. With


super(parameter list), the superclass constructor with a matching parameter list is
called. The parameters in the super keyword must match the parameters in the
super class constructer When super keyword is used it must be the first statement
in the sub class constructor.

Multilevel Inheritance

As mentioned earlier java supports multilevel inheritance. The syntax for


multilevel inheritance is given below.

class super1

------

------

class sub1 extends super1

------

34
------

class sub2 extends sub1

------

------

Example 8:

This program listed below is a simple example for multilevel inheritance.

//Super Class

class data1

int a;

data1(int x)

a=x;

//Sub Class1

class data2 extends data1

35
{

int b;

data2(int x,int y)

super(x);

b=y;

//Sub Class2

class data3 extends data2

int c;

data3(int x,int y,int z)

super(x,y);

c=z;

void compute()

System.out.println(“The Product is “ +a*b*c);

//Main Program

class Mainclass

36
public static void main(String args[])

data3 d=new data3(1,2,3);

d.compute();

Method Overriding

A subclass inherits all the methods from a superclass. Sometimes, it is necessary


for the subclass to modify the methods defined in the superclass i.e., subclass
may want to provide a new version of a method in the superclass. This is referred
to as method overriding. In a sub class, if you include a method definition that
has the same name and exactly the same number and types of parameters as a
method already defined in the super class, this new definition replaces the old
definition of the method.

Example 9:

This program listed below illustrates Method Overriding concept..

class Circle
{
double radius;
Circle(double r)
{
radius =r;
}

double getArea()
{
return Math.PI*radius*radius;
}
}
class Cylinder extends Circle
{
double length;

37
Cylinder(double radius, double l)
{
super(radius);
length=l;
}
double getArea()
{
return 2* Math.PI*radius*radius +2*Math.PI*radius*length;
}
}
class Areaprg

public static void main(String args[])

Cylinder cy=new Cylinder(3.3,5.2);

double res;

res=cy.getArea();

System.out.println(“Area of Cylinder is “+res);

When the overriden method getArea() is invoked for an object of the Cylinder
class, the new overridden version of the method is called and not the old
definition from the superclass Circle.

Output of the Program

Area of Cylinder is 176.2433478663874

38
However, if we want to find the area of both circle and cylinder then we have to
instantiate both the classes and invoke the getArea() method.

Circle c=new Circle(3.3);

c.getArea();

Cylinder cy=new Cylinder(3.3,5.2);

c.getArea();

Uses of Super Keyword

We have already learnt the usage of super keyword in invoking the super class
constructer. Super keyword can also be used to call super class method
overridden by the subclass method. The previous program is modified with the
help of super keyword.

Example 10:

This program is the modified version of the example 9

class Circle

{
double radius;
Circle(double r)
{
radius =r;
}
double getArea()
{
return Math.PI*radius*radius;
}
}
class Cylinder extends Circle

39
{
double length;
Cylinder(double radius, double l)
{
super(radius);
length=l;
}
double getArea()
{
return 2* super.getArea() +2*Math.PI*radius*length;
}
}
class Areaprg

public static void main(String args[])

double res;

Circle c=new Circle(3.3);

res=c.getArea();

System.out.println(“Area of Circle is “+res);

Cylinder cy=new Cylinder(3.3,5.2);

res=cy.getArea();

System.out.println(“Area of Cylinder is “+res);

Output of the Program

Area of Circle is 34.21194399759285

Area of Cylinder is 176.2433478663874


Super keyword can also be used to refer superclass variables. Here is an example.

40
Example 11:

The Coding given below illustrates the use of super keyword to refer superclass
variables.

class data1

int a;

data1(int x)

a=x;

//Sub Class1

class data2 extends data1

int b;

data2(int x,int y)

super(x);

b=y;

void display()

System.out.println(“Value of a is “+super.a);

System.out.println(“Value of b is “+b);

41
}

class Mainprg

public static void main(String args[])

data2 d=new data2(10,20);

d.display();

Output of the Program

Value of a is 10

Value of b is 20

Thus, we can use super keyword in the following three contexts

• To call a superclass constructer


• To call a superclass method overridden by the subclass method
• To refer the superclass variable from the subclass.

Abstract Methods and Classes

Abstract methods are those that will have only method declaration without any
implementation. Hence we can say abstract methods are incomplete methods. A

42
method in java can be declared as abstract by prefixing its declaration with the
keyword abstract. For example

abstract void area();

The implementations for these abstract methods are provided by overriding the
abstract method using a subclass.

Abstract class is a class that is declared as abstract. An abstract class will have
one or more abstract methods. Abstract classes cannot be instantiated but it can
be inherited by other subclasses. These subclasses will provide the
implementation of all the abstract methods present in the parent class however, if
not, the corresponding subclass must be declared abstract. Here is an example of
a abstract class and its corresponding subclass.

Example 12:

The Coding listed below makes use of an abstract class.

abstract class Shape

int l;

Shape()

l=10;

abstract void area(); //abstract method declaration

class Rect extends Shape

int b;

43
Rect()

b=10;

void area() //overriding the abstract method.

System.out.println(“ Area of Rect is “ +l*b);

public static void main(String args[])

Rect r=new Rect();

r.area();

Output of the Program

Area of Rect is 100


Final Keyword

Java supports an important keyword called Final. The keyword Final is used in
three different context. Final keyword can be used along with

• Variables
• Methods
• Classes

44
Final keyword when used with a variable, it becomes a constant. To declare a
variable as a “Final” prefix the keyword Final along with the variable declaration.
For example

final int PI=3.14;

When a method declaration is prefixed with the “Final” keyword the method
cannot be overridden by the subclass method. Thus method overriding can be
prevented. For example

final void calculate()

//body of th method

When a class is declared as “Final” then the class cannot be subclassed. Hence it
prevents inheritance. For example

final class test

//body of the class

Note:

A Final class can inherit other classes. For example the statement

final class test extends classA

is perfectly valid.

45
Finalizer Methods

Before an object is garbage collected, the runtime system calls it’s finalize ()
method. The purpose of finalize () method is to release system resources before
the object gets garbage collected. The signature of finalize method is given below.

protected void finalize () throws throwable

Finalize () method in java has the following properties

• every class inherits the finalize() method from java.lang.Object


• the method is called by the garbage collector when it determines no
more references to the object exist
• the Object finalize method performs no actions but it may be
overridden by any class
• normally it should be overridden to clean-up non-Java resources ie
closing a file

46

You might also like