Java OOP Basics: Classes and Objects
Java OOP Basics: Classes and Objects
Key concepts in Object oriented programming are Classes and Objects. Recall that, an object is an
entity having state, behavior and identity. Class contains instance variables and methods.
In this chapter, you will see how pure object-oriented concepts are applied using Java.
This chapter will start with declaration of classes and objects in Java. You will also see how to create
different methods.
A class has instance variables and methods. They are defined inside the class body. Braces ({ ) ) are
used to mark the beginning and the end of each class. The structure of a class is:
Rules for naming classes are exactly same as that of defining variables in [Link] are two kinds of
things that the definition of a class contains. They are instance variables and methods.
We study first instance variables and use them to define classes. Later on we add methods into these
classes.
Instance variables: These are variables that store data items, which are typically different from one object
of the class from another. For example, consider a class Employee of a company.
Class :Employee
Instance variables: emp_No , emp_Add
Method : empdetails( )
Some of the instance variables are emp_No (employee number) and emp_Add (employee address).
One of the method is empdetail( ) (Employee details).Any employee of the company will be the object of
the class. If Henna and Tina are two employees of a company then both of them can be taken as objects
of a class Employee. Henna and Tina will have different instance variables (i.e. emp_No as well as
emp_Add.)
We know that, objects are instances of a class. For example, the book, which you are reading, is the
object of the class Java books. Let us denote this object by mybook and the class by Jbook.
3.1 Operator new: When we declare an object, we mearly state its data type. For example,
Jbook mybook;
This tells the compiler that the variable mybook is an object of the Jbook class. It does not allocate
memory for the object.
To allocate memory, we need to use the new operator and the statement can be given as:
Thus to create the object of the class and allocate the memory to it, you pass two statements as:
Jbook mybook;
mybook = new Jbook();
You can combine both the statements and pass a single statement as:
(1) Declare the object and then allocate memory using the new operator.
(2) Declare the object and at the same time allocate memory using the new operator.
<class name > <object name > = new < class name > ;
After creating an object it is necessary to access the instance variables for object. This can be done
using dot operator by connecting the object name and name of instance variable as shown below:
For example: (1) For Jbook class, instance variable p_nos can be accessed using the statement:
mybook.p_nos
To assign the value say, 100 to the variable p_nos of mybook ,we can use the following statement:
mybook .p_nos = 100;
Class: Circle.
Instance variable: radius.
Method: -----------
Circle_1 Circle_2
It has an instance variable radius. Let circle_1, circle_2 be two circles with radius 2 and 3.
circle_1,circle_2 are the objects of the class circle. These objects can be created by:
Instance variable radius can be accessed for these objects using dot operator as follows:
circle_1.radius
circle_2.radius
As 2 and 3 are the radius of two circles circle_1 and circle_2 so assign them to circle_1.radius and
circle_2.radius as follows:
circle_1.radius = 2;
circle_2.radius =3;
Now you are in position to write first Java program containing classes and one object with only one
compulsory method i.e. main( ).
Example: Consider a class Rectangle with two instance variables
class Rectangle length and breadth. The class is defined as follows [See Table
{ below]:
double length; Let us find the area of a rectangle with length =10 and height =
double breadth; 20. This rectangle is the object of the class Rectangle. Let us
} denote it by myRect.
Class: Rectangle.
Instance variables: length, breadth.
Method: -------------
myRect
Every Rectangle object contains its own copies of the instance variables defined by classes. Here
every Rectangle object will contain its own copies of the instances variables viz. length, breadth. To
access these variables we use dot operators as follows:
These statements are to be written in the main( ) method of the class say, Rect_demo1.Area can be
found in usual way by writing the statement:
The complete Java program for the Rectangle class is given below:
class Rectangle
{
double length;
double breadth;
}
class Rect_demo1
{
public static void main(String args[])
{
Compile the above program by giving the name of the class in which main() method resides. i.e.
Area is 200.0
6. Methods:
The concept of methods in Java is similar to the user-defined functions in C. So far you have come
across with one method in a class called main( ). This method is compulsory and has a specific meaning.
In Java, method is a self contained block of code that has a name and has the property that it is reusable
i.e. the method can be executed as many times as you can at different points in a program. Methods are
useful to divide large calculation in small segments.
The general format of a method is:
From above you can classify the declaration of method into two parts:
In this form, the compiler executes all the lines inside the body of the
method and does not return any value to the method. For example:
void setDisplay ( )
{
[Link] (“Java is Simple”);
}
Here, Java is Simple will be printed using above method.
Consider the method Sqr to find the square of x. The variable y inside the code is called local
variable. The scope of the local variable is restricted only
void Sqr (double x) to the method. Out side the method the variable y does not
{ have any meaning.
int y;
y = x * x;
}
Rahul Deshmukh Module-2: Basics of Java Programming 5
SYBSC-Skill Enhancement Course (SEC)-25-26
Let us consider another method that has two instance variables x and y of type double.
In the above method x and y are two variables of double data type. The variable sum is a local
variable and is printed by the last line.
In this form, the compiler executes all the lines inside the body of the method and returns the value
specified by the type of the method. The format of the return statement is:
return return_expression;
(1) Here Prod is a method of computing the product of two int variables and storing
the result into local variable c.
int Prod(int a , int b)
c. The int value of c is return to the method.
{
int c;
c = a * b;
return c;
}
Alternatively, the above method can be written as:
Above examples, shows that the code returns only one value at a time. Consider the following
segment:
The method Answer( ) will return int value depending upon the condition. If there is a statement
Obj. Answer (4); in the main( ) method then x=4.
If y = 7 then as x = 4 the condition is false as 7 is not less than or equal to [Link] the control
will transfer to the else part and return the value 6 to the method. Since if result = y+ ++x − y++
then we have:
If y = 4 then as x = 7 the condition is true as 4 is less than 7. Therefore the control will transfer to the
if part and return the value 7 to the method. Since if result = y+ x++ − ++y then we have:
[Link] class:
We are now in position to write complete class containing both instance variables and methods. Let
us denote a class called Complete to find the result of the expression as shown in the adjacent box.
class Complete
{
int a,b;//instance variables
a=2;
b= 3 ;
int expression( ) //Method.
{
int result;
result= - - a + b ++;
return result;
}
Rahul Deshmukh }//end of class. Module-2: Basics of Java Programming 7
SYBSC-Skill Enhancement Course (SEC)-25-26
Explanation:
➢ The name of the class is Complete.
➢ Variables a and b are the instance variables and having values 2 and 3 respectively.
➢ Expression is a method returning int value. This method contains local variable result of int
type. The scope of this variable is restricted only for the method. In other words, this variable
cannot be accessed from out side the method as well as from out side the class.
➢ Variable result contains the expression--a +b++.
It is evaluated as follows:
Step 1: a = a - 1 = 2 - 1=1
Step 2: result= a + b =1 + 3 = 4.
Thus 4 is return to the method Expression.
➢ After return statement you should not write any statement because the control will not go to
that statement. Thus return statement must be the last statement of the method.
➢ The code of the method should be written in side the parentheses.
7.1 Accessing Methods of a class for an object:
Similar to accessing instance variables of an object, you can access methods of an object. This can be
done by:
[Link]( );
Consider the following examples:
(1) Let class_1 and class_2 be two classes having voidDisplay ( ) and main( ) methods respectively.
Let obj be the object of the class_1.Then voidDisplay ( ) method for obj can be access using the
statement:
Obj . voidDisplay( ) ;
obj
Which is inside the class_2.
class_1 class_2
Method:voidDisplay( ) main( )
(2) Let class_A and class_B two classes having mean( ) and main( ) as [Link] obj be the object of
the class_A.
Method mean( ) can be invoked
class_A for obj object by the statement
{ ……….. [Link] mean(5.0,7.0); which
double mean(double x ,double y) is inside the main( ) method of
{ the class_B.
double result ; Let us write some important
result = (x+y)/2; lines of these two classes and
return result; study them carefully. The
} //end of method. compiler will execute class_B
as main( ) method resides in it.
}//end of class.
When statement A gets
class_B executed the compiler will
{ transfer the control to the
double a; mean( ) method of the class_A.
public static void main(String args[ ] ) You can see that mean( )
{ ………….. method has two parameters x
a = [Link](5.0,7.0); // stat A and y of double type that are
…………... used to refer to the arguments
} //end of main( ) 5.0 and 7.0 respectively.
} //endDeshmukh
Rahul of class. Module-2: Basics of Java Programming 8
SYBSC-Skill Enhancement Course (SEC)-25-26
When you call the method from another method the values of the arguments passed are the initial values
assigned to the corresponding parameters. You can use any expression for the argument but note that the
data types of the arguments or expression and the data types of the parameters must be the same.
The method mean( ) declares the variable result which only exits within the body of the
method. The variable is created each time when you execute the method and it is destroyed when
execution of the method ends. All the variables declared inside the body of the method are called as local
variables. The life of these variables is only for that method. If you want to initialize these variables then
you must supply the values inside the method at the time of declaration. The code of the method mean( )
will calculate the value of the local variable result and this value is returned to the R.H.S. of the stat A.
Thus the instance variable a gets the value of result.
Here, after executing the line i =10 the control will goto the method change( ) of class C because of
statement A. Here in the definition of a method change( ) of class C,the variable j is the parameter of int
data type which will equate with the argument i having value [Link] ++j; j becomes 11,so the value of
j that is returned will be 11 and this will be stored in a.
Class: C1
Class: C
Method:main( )
Method: change ( )
obj
class C1
{
public static void main (String args[ ])
{
int i=10;
(4) Consider the classes A and B:.Stat. A transfers the control to the method product( ) which receives int
data type. Inside the body of product( ) ,c is calculated as x+2*y-1 i.e. 2+2*3-1 i.e.2+6 –1 i.e.
[Link] 7 is stored in z. See the program given below.
class A
{
-------------------
int product (int a,int b);
{
int c= a*b;
return c;
}
}
class B
{
public static void main(String args[])
{
int x=2,y=3;
int z = [Link](x+2,y-1); // stat A
}
}
8. Few complete programs:
class Rectangle
{
double length;
double breadth;
void area()
{
[Link]("Area is ");
[Link](length* breadth);
}
}
class Rect_demo2
{
public static void main(String a[ ])
{
Rectangle myrect1 =new Rectangle ( );
Rectangle myrect2 =new Rectangle ( );
myrect1 .length=10;
myrect1. breadth =20;
[Link]=15;
myrect2. breadth =24;
[Link]( );
[Link]( );
}
}
C:\Maths>javac Rect_demo2.java
C:\Maths>java Rect_demo2
Area is 200.0
Area is 360.0
class Answ
{
int x ;
int ans(int x)
{
int y=7;
if ( y<=x++)
{
int result = y+ x++ - ++y;
[Link]("x and y : "+x+" "+y);
return result;
}
else
{
int result= y+ ++x - y++;
[Link]("x and y : "+x+" "+y);
return result;
} //end of if.
} //end of method.
}//end of class.
class Answer1
{
public static void main(String args[ ]){
Answ obj = new Answ ();
[Link]("Result = "+ [Link](4) ) ; }
}
C:\Maths>javac [Link]
C:\Maths>java Answer1
x and y : 6 8
Result = 6
If x = 7 and y= 4 then
C:\Maths>javac [Link]
C:\Maths>java Answer1
x and y : 9 5
Result = 7
class Swap
Class: swap
{
int x,y;
Instance variables: x ,y
void setVar()
{
x=3;
y=4; Methods: SetVar( ),
} Display( )
void Display() Code( )
{
[Link]("x="+x);
[Link]("y="+y); obj
}
void Code()
{ class: Interchange
int t;
t=x; Method:main( )
x=y;
y=t;
}
}
class Interchange
{
public static void main(String args[])
{
Swap obj=new Swap();
[Link]();
[Link]();
[Link]();
}
}
Explanation:
➢ Swap and Interchange are two classes.
➢ Swap class contains 3 methods:
SetVar( ) assigns 3 and 4 to the instance variables x and y.
SetDisplay( ) prints x and y after swapping.
Code ( ) gives the code of interchanging the values of two variables.
➢ Interchange class contains only main( ) method.
➢ Obj is a object of a class Swap, defined in the main( ) method of Interchange [Link] obj ,you
can invoke all the three methods of the class Swap.
The keyword this is used inside the instance method to refer to the current object. The value of this
points to the object on which the current method has been called. This is useful when name of the
instance variables are the same as the list of the parameters of the methods. This can be used by the
format:
Class : This1
class This1
{
int a=7,b=10;
void Set(int a,int b)
{
this.a=a;
this.b=b;
}
void show()
{
[Link]("a= "+a);
[Link]("b= "+b);
}
}
class This
{
public static void main (String args[])
{
This1 th=new This1();
[Link](2,3);
[Link]();
}
}
Explanation:
➢ This1 and This are two classes of which main ( ) method resides in This class.
➢ Class This1 contains instance variables a and b and two methods viz. set (a,b) and Show ( )
method.
➢ Instance variables a and b are hidden by the parameters a and b of the method set ( ).
➢ th is the object defined in the main ( )method which is used to invoked methods of the class
This1.
➢ After invoking Show ( ) method 2 and 3 will be displayed as the values of a and b
[1] Containing a class with (1) instance variable without method, (2) method without instance
variable,(3) both instance variable and method.
[2] Define three classes say A, B and C such that A contains a main ( ) method, B contains code ( )
method for converting Fahrenheit to Celsius and C contains Display ( )method to show the
conversion.
[3] Define three classes say A, B and C such that A contains a main ( ) method, B contains code ( )
method for interchanging the values of two variables without temporary variable and C contains
Display ( )method to show the swap.
[4] Define two classes of your choice to count + ve numbers from a set of integers.
[5] Define two classes of your choice to find summation of a set of numbers.
[6] Define two classes of your choice of which one class contains main ( ) method and other class
contains the code for reversing the digits of an integer.
[Link]:
Constructor is a method to initialise the instance variables of the class. In other words, Constructor is a
special method to construct the object by initialising instance variables and creating the necessary
environment for the object.
For example, [1] If the class A contains instance variables x and y with a method name say method( ) to
compute the value of the expression y=x+1 then the variable x can be initialise with the method called as
constructor. We will write the full Java code later on.
Class: A
Method: method ( )
[2] If you are planning to type a document i.e. an object using Microsoft word then by default you get
font size, name of the font etc. This is called as creating environment for an object and is termed as
default constructor. You can create your own constructor by changing font size, name of the font etc. for
the object in Microsoft word.
Note that, if a class does not have any constructor method, the compiler provides the default constructor
to that class.
Rahul Deshmukh Module-2: Basics of Java Programming 15
SYBSC-Skill Enhancement Course (SEC)-25-26
1.2 Different types of Constructor:
Where the name of the constructor is the same as the name of the class in which the constructor resides.
Class: Class:Rectangle
Rect_demo5
Constructor:
Method: Rectangle( )
main ( )
myRect
Methods: Area( )
Where the name of the constructor is the same as the name of the class in which the constructor resides.
Example 1: The following program illustrates the constructor by modifying the above program.
//Parameterised constructor
class Rectangle
{
double length;
double height;
// Constructor to initialised
Rectangle ( double l , double h)
{
length = l;
height = h;
}
// Compute Area & return area
double area()
{
return length*height;
}
}
class Rect_demo6
{
public static void main(String args[ ])
{
Rectangle myRect1 = new Rectangle(10,20);
Rectangle myRect2 =new Rectangle(30,40);
double area;
// Get area of rect1
area = [Link]();
[Link]("Area = "+area);
area = [Link]();
[Link]("Area= "+area);
}
}
Class:Oper_constructor
Method: main ( ) myOper
The program is given below:
class Operator1
{ int a,b;
int sum(int x, int y)
{ int z ;
z=x+y ;
return z ; }
int product(int x, int y)
{ int z ;
z=x * y;
return z ; }
int division(int x, int y)
{ return x / y ; }
public Operator1 (int m, int n) //constructor
{ a=m ;
b=n ; }
}
class Oper_constructor
{ public static void main(String args[ ])
{
//Create and allocate memory to the object.
Operator1 myOper = new Operator1 (7,4);
// sum( ) method is invoked for myOper
[Link] ("Sum="+[Link] (2,4));
// product( ) method is invoked for myOper
[Link] ("Product="+[Link] (11,10));
// division( ) method is invoked for myOper
[Link] ("Division="+[Link] (8,3));
} }
Rahul Deshmukh Module-2: Basics of Java Programming 18
SYBSC-Skill Enhancement Course (SEC)-25-26
The output is as follows:
Save the file with: Oper_constructor under Maths
Compile the file with: C:\Maths>javac Oper_constructor.java
Run the file with: C:\Maths>java Oper_constructor
Sum=6
Product=110
Division=2
[Link]:
Suppose you have a class called Compute with three different methods of adding two variables where the
first method adds 2 integers, another method that add 2 float values and the third adds a float and a int.
These methods are doing the same job so it is appropriate to give the same name to all three methods.
This is possible using overloading technique in Java. Hence these three methods can be declared as:
Thus overloaded methods are those methods which are in the same class and have the same name but
different parameter lists.
Its name and the parameter list define a signature of the method. Thus, two methods having same name
must have different parameter list in the order to have different signatures. A class cannot have two
methods with same signature. This is because the compiler will not know which method to invoke, if
more than one method has the same signature. Java uses method overloading to implement
polymorphism.
Example1: Let us write a program to calculate the sum of different parameter list as given in the above
box.
class Compute
{
int add(int a, int b) // Method 1
{
int c;
c=a+b;
return c;
}
float add(float a , float b) // Method 2
{
float c;
c=a+b;
return c;
}
class compu_demo
{
public static void main(String args[])
{
Compute com = new Compute ();
[Link] ([Link](10,30)); //Goes to method 1
[Link]([Link](10.2f,30)); //Goes to method3
}
}
In the above program, there are three add () methods. At the time of compilation, the compiler will search
for the versions of add () method to be called based on the parameters passed.
Example 2:Consider 4 different methods with same name result( ) but contains different code. The box
diagram is as follows.
Class:Operator Class:Result_demo7
op.
//Overloading
class Operator
{
void result () //Method 1
{
[Link]("No parameter ");
}
void result (int a )
{
[Link]("a is not zero ");
}
void result (int a,int b)
{
int c;
c=a+b;
[Link]("sum of a and b is : "+ c);
}
double result (double a )
{
[Link]("Double a :"+a);
return a*a;
}
}
class Result_demo7
{
public static void main(String a[])
{
double r;
Operator op = new Operator();
[Link] ();
[Link] (7);
[Link] (10,15);
r= [Link] (12.5);
[Link]("Result of [Link] (12.5)"+r);
}
}
// method to find distance of a point from origin & from a point by method overloading
class Point
{
private double x,y;
double getDistance(Point P)
{
double dist=[Link]( (x-P.x)*(x-P.x) + (y-P.y)*(y-P.y) );
return dist;
}
void Display()
{
[Link]("X = " + x + " Y = " + y);
}
}
class DemoPoint
{
public static void main(String arg[])
{
Point p=new Point();
[Link](10,10);
Point q=new Point();
[Link](5,5);
[Link]("The point P is :");
[Link]();
[Link]("The point q is :");
[Link]();
[Link]("The d(P,Q) is : " + [Link](q));
}
}
Rahul Deshmukh Module-2: Basics of Java Programming 22
SYBSC-Skill Enhancement Course (SEC)-25-26
So far we have only been using simple types as parameters to methods. However, it is both
correct and common to pass objects to methods.
As you can see, the equals( ) method inside Test compares two objects for equality and returns
the result.
That is, it compares the invoking object with the one that it is passed. If they contain the same
values, then the method returns true. Otherwise, it returns false.
Notice that the parameter o in equals( ) specifies Test as its type. Although Test is a class type
created by the program, it is used in just the same way as Java's built-in types.
One of the most common uses of object parameters involves constructors. Frequently you will
want to construct a new object so that it is initially the same as some existing object. To do this, you must
define a constructor that takes an object of its class as a parameter.
For example, the following version of Box allows one object to initialize another:
As you will see when you begin to create your own classes, providing many forms of constructor
methods is usually required to allow objects to be constructed in a convenient and efficient manner.
In general, there are two ways that a computer language can pass an argument to a subroutine.
The first way is call-by-value. This method copies the value of an argument into the formal parameter of
the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the
argument used to call it.
The second way an argument can be passed is call-by-reference. In this method, a reference to an
argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference
is used to access the actual argument specified in the call. This means that changes made to the parameter
will affect the argument used to call the subroutine.
As you will see, Java uses both methods, depending upon what is passed. In Java, when you pass
a simple type to a method, it is passed by value. Thus, what occurs to the parameter that receives the
argument has no effect outside the method.
For example, consider the following program:
As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10. When you pass an object to a method, the
situation changes dramatically, because objects are passed by reference. Keep in mind that when you
create a variable of a class type, you are only creating a reference to an object.
Thus, when you pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument. This effectively means that objects are passed to methods
by use of call-by-reference. Changes to the object inside the method do affect the object used as an
argument.
As you can see, in this case, the actions inside meth( ) have affected the object used as an
argument. As a point of interest, when an object reference is passed to a method, the reference itself is
passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that
value will still refer to the same object that its corresponding argument does.
Note - When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed
by use of call-by-reference.
Returning Objects
A method can return any type of data, including class types that you create.
For example, in the following program, the incrByTen( ) method returns an object in which the
value of a is ten greater than it is in the invoking object.
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
ob2 = [Link]();
[Link]("ob2.a after second increase: " + ob2.a);
}
}
As you can see, each time incrByTen( ) is invoked, a new object is created, and a reference to it
is returned to the calling routine.
The preceding program makes another important point: Since all objects are dynamically
allocated using new, you don't need to worry about an object going out-of-scope because the method in
which it was created terminates. The object will continue to exist as long as there is a reference to it
somewhere in your program. When there are no references to it, the object will be reclaimed the next
time garbage collection takes place.
Examples-
(1) What are constructors? How they are different from methods? Can you overload the constructor?
(2) Can you call one constructor from another?
(3) What is overloading? Give one example.
INHERITANCE
Starter: In the previous chapter you learn two special methods viz. constructors and overloading. In this
chapter you will see the implementation of the object oriented programming feature namely, Inheritance
via Java.
Land Air
Vehicle Vehicle
You can incorporate the structure and behaviour for these two classes to form a new class called the
super class. The superclass contains generalised properties taken from the class called sub class.
Subclass contains specialised property, which are not taken into the superclass.
A superclass is a class from which another class inherits properties. It shares its properties with its
child classes. A subclass is a class that inherits attributes and methods from a superclass.
A subclass does not inherit the constructors of the superclass, since, constructors hold a special
meaning to the compiler. Subclasses may also have their own instance variables & methods besides
those, which are inherited from the super class. Super class is referred to as parent class or base class and
subclass as a derived class or child class.
There are four types of inheritance: -
1. Single Inheritance
2. Multiple Inheritance ( Several Super classes )
3. Multilevel Inheritance
4. Hierarchical Inheritance
1. Single Inheritance: Here there is only one super class and subclasses are derived from the super
class. i.e. one subclass is derived from only one super class.
Super Class A
B
Subclass
For example, Car & Truck are 2 subclasses derived from the super class Vehicle.
Vehicle
Supe
r
Car Truck
class
Sub classes
Rahul Deshmukh Module-2: Basics of Java Programming 31
SYBSC-Skill Enhancement Course (SEC)-25-26
2. Multiple inheritance: Here there are several super classes and the subclasses are derived from more
then one super class.
For example a subclass child inherits the properties from the super class Father and Mother. Java does
not support Multiple Inheritance.
Sub
Child class
However Java does not support directly implement multiple inheritance. It is implemented in
the form of Interfaces Chapter.
Subclasses are derived from the super class using the key word called extends. The general format is:
Super
class supobj
Sub
subobj class
C:\Maths>javac Single_Inher.java
C:\Maths>java Single_Inher
Content of Superclass: a= 6 b= 8
Content of Subclass: a= 2 b= 3 c= 4
sum of a,b and c is:9
A subclass can be invoked by a constructor method of the super class by the keyword super with
the following format:
super (list of parameters);
Thus if super_class is a super class and sub_class is a sub class then we have,
class super_class
{
super_class (list of variables)
{
---------
}
}
class sub_class extends super_class
{
sub_class (list of variables)
{
super (list of variables);//line 1 of the subclass constructor
}
}
Example: Consider the super class Rectangle and the sub class Box defined by the following box
diagram:
class Rectangle
{
int length;
int breadth;
Rectangle (int a, int b) //constructor of
{ super class
length = a ;
breadth = b;
}
int area ( ) //method in super class
{
return(length*breadth);
}
}
class Box extends Rectangle
{
int height;
Box(int a, int b, int c ) //constructor of sub class
{
super (a,b );//passing values to super class
height = c;
}
int volume ()
{
return (length*breadth*height);
}
}
class Inher_demo
{ public static void main(String[] args)
{
Box bo= new Box (12,14,17);
int area1= [Link]();//super class method
int volume1=[Link]();//subclass method
[Link](" Area = " + area1);
[Link](" Volume = "+volume1);
}
}
[Link];
Where the member might be an instance variable or method
Consider the super class Outer and the sub class Inner as shown in the following box diagram:
Class: Inner
Class: Outer
Instance variables: i
Instance variables: i , j
Constructor: Inner ( )
Method: show( )
Method: show ( )
Super
class Sub
obj class
Class : Super_Demo
Method: main( )
Following is the complete program where the method show ( ) will be accessed from Inner class.
Class Outer
{ int i,j ;
void show ()
{
[Link](“Super i = “ +i );
}
} // end of Outer class
class Inner extends Outer
{
int i ; // this i hides the i in the outer class
Inner (int a, int b) // constructor of Inner
{ super.i = a ;// i is from the OuterClass
i = b; // i is from the InnerClass
j=a; // j is from the OuterClass
} //end of constructor
void show()
{ [Link](" i from super class " + super.i);
[Link](" i from subclass and j from super class: " + i +" and "+j );
}
} // end of Inner class
class super_demo
{ public static void main(String[] args)
{ Inner obj= new Inner (10,20);
[Link]( ); } }
Save the file :super_demo.java under Maths
Compile with:javac super_demo.java
Run with: java super_demo The output is as follows:
Rahul Deshmukh Module-2: Basics of Java Programming 36
SYBSC-Skill Enhancement Course (SEC)-25-26
C:\Maths>javac super_demo.java
C:\Maths>java super_demo
i from super class: 10
i from subclass and j from super class: 20 and 10
3. Multilevel Inheritance – A subclass is derived from another derived class or subclass. It uses a
derived class or subclass as a superclass.
4 Hierarchical Inheritance
Many subclasses are derived from one superclass.
B C D
Example –
We have seen that overloaded methods are those methods, which are in the same class and have the
same name but different parameter lists. On the other hand, if methods are in super class as well as in
subclass then these methods are called as overriding methods.
For example, consider a class Shape as a super class. Let rectangle and circle be two derived
classes from the Shape class. Suppose CompuetArea ( ) is a behaviour of the Shape class. There are
different formulae to calculate the area for different shapes. Therefore the ComputeArea ( ) method is
invoked in different ways in the classes rectangle and circle.
ComputeArea ( )
Rectangle circle
Superclass
Subclass
subobj
suo
Class:Override
Method:main ( )
class A
{
int i,j;
A{int a, int b) //constructor
{
i=a;
j=b;
}
//display i and j
void display( )
{
[Link](" i and j ; " + i + " " + j );
}
}
class B extends A
{
int k;
B(int a, int b, int c ) //constructor
{
super (a,b); //invoking from constructor A
k=c;
}
//display k-- this overrides display() of A
void display()
{
[Link](" k : " + k );
}
}
class override
{
public static void main(String[] args)
{
B subobj = new B (1,2,3);
[Link]();//this calls display() of B
}
}
Let us execute the program and then run it by giving following commands:
C:\Maths>javac [Link]
C:\Maths>java override
K=3
If you insert this code into the previous program, then you will get the following output
i and j : 1 2
k:3
Here [Link] ( ) statement plays an important role and sends the control to super class A
and displays i and j of A.
2. Overriding methods occur if and only if the name and the type of signatures of the two methods are
identical. If they are not then the two methods are said to be overloaded. For example, modify the above
program as follows:
Sub class: B
Super
Super class:
class: A A
Instance variables: i,j Instance variables: k
Instance variables: i,j
Constructor: (a,b) Constructor: B(a,b,c)
Constructor: A(a,b)
Method: display()
Method: display()
Method: display()
Let us execute the program and then run it by giving following commands:
C:\Maths>javac [Link]
C:\Maths>java override1
This is k : 3
i and j : 1 2
The code of display in B takes a string parameter. This makes its type signature different from the one in
A, which takes no parameters. Therefore no overriding (name hiding) takes place.
In real life it is difficult to imagine the model of a given object. For instance, you know that
rectangle, circle and parabola are the objects of the class shape. If some one asks you how the rectangle
looks like? You will immediately answer that “A rectangle is a 2- dimensional figure having length and
breadth”. Area and perimeter can be found for rectangle. But if someone asks you how would you
describe a shape? Then you will not have answer as shape is abstract and can’t be properly defined like
circle, parabola. There are many classes, which are abstract. For example, Vehicle, mammals are
abstract classes.
Abstract class is a super class and has generalised properties. In Java abstract class is defined
using the keyword abstract .For example, the class shape can be defined as:
Class: Shape
Method: area ( )
C:\Maths>javac abstract_demo.java
C:\Maths>java abstract_demo
Area of triangle is 4.0
Area of circle is 588.0
final class A
{ void display()
{
[Link](“ In show of A “);
}
}
class B extends A // error class should not be inherited
{ void display()
{
[Link](“ In show of B “);
}
}// can’t found output.
Normally a member must be accessed only in conjunction with an object of its class. It is
possible to create a member that can be used by itself, without reference to a specific instance. To create
such a member, precede its declaration with the keyword static. When a member is declared as static,
it can be accessed before any objects of its class are created. Both methods and variables of a class
can be declared as static. The most common example of a static member is main() .
Instance variables declared as static are, essentially, global variables. When objects of its class are
declared no copy of a static variable is made. Instead, all instances of the class share the same static
variable.
In order to initialize static variables, a static block is declared, which gets executed exactly once.
Example
To call a static method from outside the class use the following form :
[Link]();
classname is the name of the class in which the static member is defined.
Eg: [Link]();
Java uses a procedure called garbage collection to reclaim memory occupied by objects that are
no longer accessible to a program. It is the responsibility of the system, not the programmer, to keep track
of which objects are "garbage". In the above example, it was very easy to see that the Student object
had become garbage. Usually, it's much harder. If an object has been used for a while, there might be
several references to the object stored in several variables. The object doesn't become garbage until all
those references have been dropped.
In many other programming languages, it's the programmer's responsibility to delete the garbage.
Unfortunately, keeping track of memory usage is very error-prone, and many serious program bugs are
caused by such errors. A programmer might accidently delete an object even though there are still
references to that object. This is called a dangling pointer error, and it leads to problems when the
program tries to access an object that is no longer there. Another type of error is a memory leak, where a
programmer neglects to delete objects that are no longer in use. This can lead to filling memory with
objects that are completely inaccessible, and the program might run out of memory even though, in fact,
large amounts of memory are being wasted.
Because Java uses garbage collection, such errors are simply impossible. Garbage collection is an old
idea and has been used in some programming languages since the 1960s. You might wonder why all
languages don't use garbage collection. In the past, it was considered too slow and wasteful. However,
research into garbage collection techniques combined with the incredible speed of modern computers
have combined to make garbage collection feasible.
The finalize Method
Some times an object will need to perform some action when it is destroyed. To handle such situations,
java provides a mechanism called finalization. By using finalization one can specify the actions that will
occur when an object is just about to be reclaimed by the garbage collector. To add finalizer to a class
simply define finalize() method. The java runtime calls that method whenever it is about to recycle an
object of that class. Inside the finalize() method, code is specified for actions that must be performed
before an object is destroyed.
Syntax
[1] What do you understand inheritance in Java? What are their advantages? What are the different forms
of inheritance? Does Java support all of them?
[2] Consider the class hierarchy class1 --- class2--- class3. Assume that all classes contains a method
called as show ( ) and if you want to call the method show ( ) of class2 and class3 then how you will
proceed?. How can you call the constructors of class2 and class3?
[3] What does overriding mean?
[4] What do you mean by abstract class? Can an abstract class contain method with body? Can you call a
variable as abstract?
[5] What do you mean by final variable and final method?
ACCESS SPECIFIERS
The feature of a class (the calls itself, instance variable, and methods) used by other classes is
called access specifies. Java supports three access specifies
1. public access specifier
2. private access specifier
3. protected access specifier
We know that the scope of variable and methods is for the entire class. To make this scope
available to all the classes outside this class you can define variable or method as public. For example,
All the classes except inner classes have the public access specifier
to make the scope of the members (instance variable and methods )restricted to the class you can use
private access specifier. Variables and methods can be made private and their scope is only for that class.
Thus these members can't be inherited into subclasses if members of the class are defined as private. A
method declared as private behaves like a method declared as final.
This modifier is the most restrictive access modifier. Note that the top level class in the
inheritance hierarchy is never declared as private. The members can be declared as private by the
following example:
private int add(int a, int b ){… …}
Consider the following example:
class Pubpri
{ void int a; //default access
public int b;//public access
private int c;//private access
void setDimC(int i)
{
c=i;
}
int getc() Class: pubpri
{
return c; Instance variables:
} a - void,b -public, c- private
class Access_Pubpri Methods: Set DimC(i) for c.
{ getc()
public static void main(String[ ] args)
{ Class: access pubpri public
Pubpri obj = new Pubpri(); method
obj.a =1;//this is possible
obj.b=2;//this is possible
obj.c=3; // this will give an error
[Link](10);//this is possible
[Link]("a,b,and
c:"+obj.a+obj.b+[Link]());
}
}
Rahul Deshmukh Module-2: Basics of Java Programming 50
SYBSC-Skill Enhancement Course (SEC)-25-26
Variable methods and inner classes that are declared protected are accessible to the subclasses of
the class in which they are declared. For example,
Protected int [Link];
Consider the following set of classes. Class B and C are inherited from class A. class c belongs to
the package F1 which is a collection of classes P1 and classes A and B belong to the package P2.
Suppose a method My method( ) is in the class A . The following table shows you accessibility of
the method my method from classes B and C.
Class A
Package2
Class B
Class C
Access Location
4. Friendly Access:
In previous examples, we have not used public modifier but then members are accessible to
other classes in a program. When no access modifier is specified, the member defaults to a limited
version of public accessibility known as “Friendly” level of access.
The difference between the ‘public’ access and the ‘friendly’ access is that the public
modifier makes scope of members accessible to all the classes regardless of their package. On the
other hand the friendly access makes scope of member accessibility only in the same package, but
not in other package.
Starter: The programmer always makes mistakes in typing or in the logic of the program. It is rare that
the program run successfully at the first attempt. A mistake might lead to an error causing the program to
produce unexpected results.
Following are two types of errors:
Compile-time error.
Run-time error.
Let us study one after another.
11.1 Compile-time error:
Java compiler handles the errors like syntax errors, missing semi colons (;), missing brackets for the
methods or for the classes etc. at the time of the compilation of the program and therefore these
errors are termed as Compile-time error.
11.2 Run-time error:
Some times, Java program may compile successfully by creating the. class file but may not run.
Such programs may produce wrong results due to wrong logic or may terminate due to errors such
as stack over flow. These errors are termed as run time error. Some of the run time errors are
dividing an integer by zero, accessing an element that is out of bounds of an array etc.
Consider the following simple example where run-time error has occurred.
P
class Error
{
public static void main( String args [ ])
{
int x = 14;
int y = 6;
int z= 6;
int result = x/(y-z); /* Division by zero */
[Link]( “Result =”+result);
int ans = x/(y+z); /*This is sensible */
[Link]( “Answer =”+ans);
}
}
The above program does not have any serious error and you will not get any compile-time error.
The programmer is expecting an output after running the program, but will be disappointed as the
computer will shout and display the following message.
When Java run-time tries to execute a division by zero, it generates an error condition, which causes the
program to stop after displaying an appropriate message.
11.3 What are Exceptions and call stack?
Java supports run-time error mechanism known as Exceptions. Run time errors occur at the time
of the running of the program. These errors are handle by writing block of code so, if error occurs then
this block take care of this error and execute the remaining portion of the program. In Java, there is a
mechanism to handle these exceptions which you are going to learn in this chapter.
try
{
Block of statements where possible
exception has occured;
}
catch ( Exception_type object )
{
Block of statements to catch the
exception occurred in try block;
}
try
{
ans=a/b;
}
catch(ArithmeticException e)
{
[Link](“Division is not possible”);
}
Example1: Following program illustrates the catch and try block, where try block guards the
arithmetic expression and throws an exception object in catch block.
class mistake1
{
public static void main( String args [ ])
{
int x = 14;
int y = 6;
int z= 6;
try
{
int result = x/(y-z); /* Division by zero */
}
catch(ArithmeticException e)
{
[Link]( "Division by zero");
}
int ans = x/(y+z); /*This is sensible */
[Link]( "Answer ="+ans);
}
}
How the program works?
• x,y and z are declared as int variables taking values 4,6 and 6 respectively.
Rahul Deshmukh Module-2: Basics of Java Programming 55
SYBSC-Skill Enhancement Course (SEC)-25-26
• try block contains only one statement for finding the integer value of the expression and assigning it
to result. This statement is guarded using try block. If an exception occurs then the control will shift
to catch block. Here the exception has occurred as the denominator is zero.
• The exception is of Arithmetic in nature so the object e of ArithmeticException is taken inside the
bracket after the keyword catch.
• ans is the int variable holding the value of the expression given on the R.H.S. The question will
definitely come in your mind that, why this statement is written after the try/catch block and why not
inside the try block as the statement, after the value of the result is found. The answer of this question
will be given in the next example.
Compile the above program by giving the command:
C:\MATHS >javac [Link]
Run the above program by giving the command:
C:\MATHS >java mistake1
Division by zero
Answer =1
Example 2:Let us insert the expression for ans inside the try block as follows:
class mistake2
{
public static void main( String args [ ])
{
int x,y,z;
int result,ans;
x=[Link](args[0]);
y=[Link](args[1]);
z=[Link](args[2]);
try
{
result = x/(y-z);
ans = x/(y+z);
}
catch(ArithmeticException e)
{
[Link]( "Division by zero");
}
[Link]( "Answer ="+ans);
} }
The above example shows that if exception occurs in any of the statement of the try block, the
control will switch to the catch block by ignoring all the statements ahead of the statement where the
exception has occurred. This problem can be solved using the keyword finally, which you will see later
on.
11.5 Multiple catch statements:
For one try block, it is possible to write more than one catch block. If the program generates
more than one exception then multiple catch statements are required. These catch statements are searched
by the exception thrown in order. The first matching catch clause is executed. Lastly, if the exception
doesn’t find a matching catch clause then it is passed to default handler. The general format is:
try
{
Block of statements where possible
exception has occured;
}
catch ( Exception_type1 object )
{ Block of statements to catch the
exception occurred in try block;
} catch ( Exception_type2 object )
{ Block of statements to catch the
exception occurred in try block;
}
catch ( Exception_type3 object )
{ Block of statements to catch the
exception occurred in try block;
}
You can have more catch blocks.
Example3: Consider the following program to find the value of the array expression, which is
assigned to the variable x.
class mistake3
{ public static void main(String args[])
{ int x[ ] = { 2 , 4 };
int y = 4;
try
{
int a = x[1]/x[2]-y;
}
catch(ArithmeticException e)
{
[Link]("Division by zero!");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array Index Error!");
}
catch(ArrayStoreException e)
{
[Link]("Wrong data type!");
}
int b = x[1]/x[0];
[Link]("b
Rahul Deshmukh = "+b ); Module-2: Basics of Java Programming 57
}}
SYBSC-Skill Enhancement Course (SEC)-25-26
try
{
int x=y/z; /*Exception occurred */
int a=b*c ;
}
catch( ArithmeticException e)
{
/* process the exception */
}
Here the value of the variable a is to be calculated irrespective of whatever an exception is raised or not.
To find the value of a, you can write this statement out side the try and catch block [as done in the class
mistake2]. The problem is that this statement is not guarded so an exception may occur. To guard this
statement you can use the block called finally. This block can be used to handle any exception occurred
in the try block. The finally block may be added immediately after the try block or after the last catch
block. Thus, you can write finally block as shown below:
try
{
int x=y/z; /*Exception occurred */
}
finally
{
int a=b*c ;
[Link](“Value of a is :”+ a);
}
Thus whether x is zero or not you will definitely get the value of a.
Examples 4: Consider the following program:
class mistake4
{
public static void main( String args [ ])
{
String name;
float a,b;
try
{
name=new String( " Sushil Maths. " );
a=[Link](args[0]);
b=[Link](args[1]);
[Link]( name);
[Link]( "Division is "+a/b);
}
catch(ArithmeticException e)
{
[Link]( "Division by zero not possible!");
}
finally
{
name=null;
[Link]( "Finally Executed!");
}
}
}
In the above program, you can see that after executing the try/catch block the control shifts automatically
to the finally block irrespective of an exception.
Execute and run the above program as follows:
C:\MATHS>javac mistake4
C:\MATHS>java mistake4 2 3
Sushil Maths.
Division is 0.6666667
Finally Executed!
Rahul Deshmukh Module-2: Basics of Java Programming 59
SYBSC-Skill Enhancement Course (SEC)-25-26
As there is no exception so the control goes to finally block and get the above result.
Let us run the program again as follows:
Example5: Following program contains the use of try/catch/finally blocks using constructor:
class mistake5
{
String name;
int a,b;
mistake5(String args[ ])
{
try
{
name=new String( " Sushil Maths. " );
a=[Link](args[0]);
b=[Link](args[1]);
[Link]( name);
[Link]( "Division is "+a/b);
}
catch(ArithmeticException e)
{
[Link]( "Division by zero not possible!");
}
finally
{
name=null;
[Link]( "Finally Executed!");
}
}
public static void main( String args [ ])
{
new mistake4(args);
}
}
For example, In the previous programs ArithmeticException is used, which is the subclass of Throwable
[Link] you can write:
catch (MyException e )
{
---------
---------
}
Program
11.8 Use of throws:
Whenever a programmer does not want to handle exceptions using the try block then the throws
clause along with the main ( ) method can be used as follows:
The throws clause is responsible to handle the different types of exceptions generated by the
program. This clause contains list of various types of exceptions that are likely to occur in the program.
Consider the following example:
class mistake6
{
public static void main (String args[]) throws ArithmeticException
{
[Link]("Inside the main");
int i=0;
int j=12/i;
[Link]("This statement is not printed");
}
}
After executing and running the program you get:
C:\MATHS >javac [Link]
C:\MATHS>java mistake6
Rahul Deshmukh Module-2: Basics of Java Programming 61
SYBSC-Skill Enhancement Course (SEC)-25-26
Inside the main
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
Review Questions:
1. Define an exception.
2. Explain the use of try and catch clause.
3. How do you define a (i) try, (ii) catch block?
4. List some of the most common types of exception that occurs in Java. Give examples.
5. Is it necessary to catch all types of exceptions?
6. Is it possible to have more than one catch block with one try block?
7. What do you understand by a finally clause? What is the use of this clause? Give suitable example.
Try your self:
1. Create a try block that can generate two types of exception and then incorporate necessary catch
blocks to catch and handle them accordingly.
2. Define an exception called “No MatchException” that is thrown when a string is not equal to
“Pakistan”. Write a program that uses this exception.
3. Create a user-defined exception, which is to be generated whenever the user inputs the string “I am
fool”.
4. Write a program to illustrate the usage of (i) try and catch blocks,(ii) try, catch and finally blocks.
Starter: You have learned so far Java programs of applications. These programs are executed using MS-
DOS or UNIX prompt. Now in this chapter, you will learn Java programs that run inside a WebPages.
These programs are called as Applets. You will also see the package called as [Link].* containing
Graphics class with different methods.
In an applet the line of text or string can be inserted using the method drawString ( ) of the class
Graphics of awt package. The syntax of this method is:
For example,to place the line “ Applet is still not created” starting from (20,40) the following method
is used:
<HTML>
This line <APPLET CODE ="My_applet.class"
tells the WIDTH=250 HEIGHT=250 > browser
that the file is a
</APPLET>
hypertext mark-
up document. </HTML>
Applet. When an applet is loaded, it goes through certain changes in its state of an applet:
(1) The init ( ) state
(2) The start ( ) state
(3) The paint ( ) state
Let us study these states one after another.
import [Link].* ;
import java .awt.* ;
public class Our_Applet extends Applet
{
String disp_str1,disp_str2;
public void init ( )
{
disp_str1="Smell of Java";
disp_str2="Author: Sushil Maths";
}
public void paint(Graphics g)
{
[Link](disp_str1,50,20);
[Link](disp_str2,50,50);
}
}
Open the file [Link] that you have already created. In this file replace the applet Code as
“name_applet.class” and run this file by giving the command:
C:\ Maths \ Apple>appletviewer [Link]
//Cont..
public void stop( )
{
stopcount++;
repaint();
}
public void destroy( )
{
destroycount++;
repaint( );
}
public void paint (Graphics g)
{
[Link]("init has been invoked"+
[Link](initcount)
+ "times",20,20);
[Link]("start has been invoked"+
[Link](startcount)
+ "times",20,35);
[Link]("stop has been invoked"+
[Link](stopcount)
+ "times",20,50);
[Link]("destroy has been invoked"+
[Link](destroycount)+"times",20,65);
}}
Save the above program by giving the name Applet_Method.java under the directory Maths\Apple
Compile the program by the command:
javac Applet_Method.java
Create the HTML file and run that file by the command:
appletviewer [Link]
The output is as follows:
In Java applications you have learn how to pass parameters. You can pass parameters to the
applets by the following two things:
❖ In an applet program init ( ) method contains a method called as getParameter ( ).This method is
used by the following signature:
variable1=getParameter (“variable2”);
Where variable1 is the string variable and variable2 is the string const., which is assigned to
NAME in the HTML file.variable1, can be taken as a string const.
For example,
(i) str= getParameter (“college” ); or
college= getParameter (“college” );
(ii) svar=getParameter (“marks”); or
marks=getParameter(“marks”);
Note that if the parameter is an integer, then it has to be converted into string and passed on as
parameter to the getParameter ( ) method.
❖ The special parameter tag <PARAM> is to be created in HTML file by the following format:
For example,
(i) <PARAM NAME= College
VALUE=” Jai Hind”>
(ii) <PARAM NAME= marks
VALUE=” 72”>
import [Link].*;
import [Link].*;
public class Passpara extends Applet
{
String strname="Mehir"; //initialization
public void init ( )
{
String name;
strname=getParameter ("strname");
if( strname==null)
strname = "No Name Entered.";
strname="What is your name?: "+strname;
}
public void paint (Graphics g)
{I
[Link]([Link]); //learn this method later.
[Link](strname,50,50);
}
}
You know that the [Link] package contains the class called Graphics for drawing strings,
lines, rectangles and other shapes. This package also contains Font and color classes besides
Graphics class. In this article you will learn Font and color classes.
Fonts are used to display the text in different forms Font class contains various methods. You
will deal with some of them.
This class contains wide variety of fonts like Times Roman, Courier, Helvetica, Palatino etc.
and some of the font styles available in this class are PLAIN, BOLD, ITALIC. These are integer
constants and so you can add them. For example, if you want the text to be printed BOLD as well as
ITALIC then you can write, [Link]+[Link].
Rahul Deshmukh Module-2: Basics of Java Programming 71
SYBSC-Skill Enhancement Course (SEC)-25-26
If the font is not specified then the system chooses Courier as the font for the text.
[A]To display the text using necessary font the following constructor is
used:
Where obj is the instance of the class Font, name_font denotes the object of the family of fonts, style
may be PLAIN, BOLD or ITALIC and size is the font size.
For example,
(i)
Font f = new Font (“ Serif ”, [Link], 30);
means the text will be displayed with Serif font with style as BOLD and size 30.
(ii)
Font f = New Font(“ Impact ” ,[Link] + [Link],40);
means the text will be displayed with Serif font with style as BOLD as well as ITALIC and size 30.
[B]The method used to set the font is:
[Link] (obj2);
Where obj1 is the instance of the class Graphics and obj2 is the instance of the class Font.
For example,
[Link](f);
Where g is the instance of the class Graphics and f is the instance of the class Font.
Following example illustrates the above constructor and the method:
In this program, the text line “I am learning JAVA” is displayed from the point (50,50) on the
screen. This text line is displayed with the font dialog of bold type and point size 30.
import [Link].*;
import [Link].*;
public class Font_applet extends Applet {
Font f = new Font ("Dialog",Font .BOLD,30);
public void paint(Graphics g)
{
[Link](f);
String str="I am learning JAVA";
[Link](str,50,50);
}
}
Save the above program by giving the name
Font_applet.java
under the directory Maths \Apple
Compile the program by the command:
javac Font_applet.java
Create the HTML file by giving the name
no_appet1.html
as follows: <HTML>
<APPLET CODE="Font_applet.class"
WIDTH=400 HEIGHT=150>
</APPLET>
</ HTML>
Rahul Deshmukh Module-2: Basics of Java Programming 72
SYBSC-Skill Enhancement Course (SEC)-25-26
The output is as follows:
Let us write the program to display two text lines with two different constructors and two different
methods.
Note that the constructors are defined in paint ( ) method.
import [Link].*;
import [Link].*;
public class Font_applet1 extends Applet
{
public void paint(Graphics g)
{
Font f1 = new Font ("Serif",[Link]+Font. ITALIC,40);
[Link](f1);
String str1="I am learning JAVA";
[Link](str1,20,50);
You can set colour to the text in an applet using following syntax:
[Link](Color.<name_colour>);
white black
orange gray
lightGray darkGray
red green
blue pink
cyan magenta
yellow
import [Link].*;
import [Link].*;
public class Font_applet2 extends Applet
{
Font f2 =
new Font("MSOutlook",[Link]+[Link],40);
[Link](f2);
String str2="From Smell Of JAVA";
[Link]([Link]);
[Link](str2,20,90);
Font f3 =
new Font( “Garamond",[Link]+[Link],40);
[Link](f3);
[Link]([Link]);
String str3="Author: Sushil Maths.";
[Link](str3,20,140);
}
}
Save the file as Font_applet2.java under Maths\applet and compile it. Create the HTML file
as Font_applet2.html under Maths\applet as follows:
Before going to different methods to draw lines, ovals, rectangles Polygons [Link] try to
understand co-ordinate system of Java.
The upper left corner of the monitor screen is called as the origin of the Java’s co-ordinate
system and is denoted by O (0,0).[See [Link] below.)
(x ,y )
+ve Y axis
In this system, x coordinate is the distance moving right from the origin and y coordinate is
the distance moving down from the origin. The point (x,y) is a +ve ordered pair where both x and y
are + ve integers. Any shape or diagram can be drawn on a screen by specifying an ordered pair.
A line can be drawn using Graphics class of [Link] package by the following method:
(x1,y1)
(x2,y2)
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:
Execute the above HTML file using appletviewer. The output is as shown in the following figure.
An Oval can be drawn using Graphics class of the [Link] package as follows:
drawOval ( int x , int y, int width, int height);
Here there are 4 parameters to draw an Oval. An oval starts with the co-ordinates (x, y) and width,
height are the width and height of an oval. The oval can be coloured by setColor ( ) method.
Oval can be filled by the colour using the method with the same 4 parameters as above. The method
can be written as:
fillOval ( int x , int y, int width, int height);
For example,
1. drawOval (100,200,70,40);means the an oval starts from the point (100,200) with width 70 and
height 40.
2. fillOval (200,200,70,90);means the an oval starts from the point (200,200) with width 70 and
height 90.
If you wish to draw a circle or filled circle then you have to take width equal to height.
Following program illustrates these methods.
import [Link].*;
import [Link].*;
public class Drawoval extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](50,50,80,50);
[Link]([Link]);
[Link](150,50,50,100);
[Link]([Link]);
[Link](50,50,80,80);
[Link]([Link]);
[Link](150,170,50,50);
}
}
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:
Execute the above HTML file using appletviewer. The output is as shown in the following
figure.
A rectangle can be drawn using Graphics class of the [Link] package as follows:
drawRect ( int x , int y, int width, int height);
Here there are 4 parameters to draw a rectangle. A rectangle starts with the co-ordinates (x, y) and
width, height are the width and height of a rectangle The rectangle can be coloured by setColor ( )
method.
A rectangle can be filled by the colour using the method with the same 4 parameters as above. The
method can be written as:
For example,
1. drawRect (50,100,70,40);means a rectangle starts from the point (50,100) with width 70 and height
40.
2. fillRect (100,200,70,90);means a rectangle starts from the point (100,200) with width 70 and height
90.
If you wish to draw a square or filled a square then you have to take width equal to
height.
You can also draw round rectangle and fill it by the following methods:
Here, method got 6 parameters, of which the first 4 parameters are the same as the
drawRect ( ) method. The addition two are:
1. arcwidth: This is used to round off the leftmost and rightmost corners of the rectangle.
2. archeight: This is used to round off the topmost and bottommost corners of the rectangle.
Following program illustrates these methods.
import [Link].*;
import [Link].*;
public class Drawrect extends Applet{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](50,50,60,90);
[Link]([Link]);
[Link](150,50,50,100,20,40);
[Link]([Link]);
[Link](50,150,70,70);
[Link]([Link]);
[Link](150,170,70,50,30,40);
}
}
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:
Execute the above HTML file using appletviewer. The output is as shown in the following
figure.
13.9.4 Applications:
In this article you will see the applications of all the methods seen above.
Example1: (Creating a hut) let us write a program to create a small hut. The code is given below:
import [Link].*;
public class hut extends [Link]{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](200,20,60,130);
[Link]([Link]);
[Link](100,100,300,100);
[Link]([Link]);
[Link](340,130,200,20);
[Link]([Link]);
[Link](100,100,200,200);
[Link]([Link]);
[Link](160,200,80,100);
[Link]([Link]);
[Link](80,300,240,50);
}
}
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:
import [Link].*;
import [Link].*;
public class Man extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](150,50,100,100); //Face
[Link](200,150,200,300); //body
[Link](200,200,125,275);//left hand
[Link](200,200,275,275);//right hand
[Link](200,300,125,375);//left leg
[Link](200,300,275,375);//right leg
[Link]([Link]); //colour of eyes
[Link](210,70,20,20);//left eye
[Link](170,70,20,20);//right eye
[Link]([Link]);
[Link](200,90,200,110);//nose
[Link](200,110,195,106);//nose
[Link]([Link]);
[Link](180,120,35,10);//mouth
[Link]([Link]);
[Link](80,340,250,75);/*table top */
[Link](120,408,10,50); /* left leg of table */
[Link](260,412,10,50); /* right leg of table */
}
}
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:
Execute the above HTML file using appletviewer. The output is as shown in the following
figure.
save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:
Execute the above HTML file using appletviewer. The output is as shown in the following
figure.
The answer of the above question is “ YES “. Following code shows by drawing 5-circles
using for loop. Here 5 circle are touching each other externally.
import [Link].*;
import [Link].*;
public class Circle5 extends Applet {
public void paint(Graphics g)
{
for(int i=0;i<=4;i++)
{
// If circle is at even position colour it red else blue.
if((i%2)==0)
{
[Link]([Link]);
[Link](130,i*50+20,50,50);
}
else
{
[Link]([Link]);
[Link](130,i*50+20,50,50);
}
}
}
}
Save the file as [Link] under Maths\applet and compile it. Create the HTML file as
[Link] under Maths\applet as follows:
Execute the above HTML file using appletviewer. The output is as shown in the following
figure.
To draw an arc, Graphics class contains a method called as drawArc ( ) .This method works
similar to the method drawOval ( ).In this case, the arc is taken as an Oval and hen draw only a
part of it as dictated by the last two parameters of the
drawArc ( ) method. The first four parameters are the same as drawOval ( ) [Link] is
given as:
445
180 0
270
For example, to draw an arc from an angle 45 degrees to 180 degrees then starting angle would
be 45 and the swap would be 135 [since (45 to 90 it is 45) +(90 to 180 it is 90)]. The method can be
given as
drawArc(80,120,60,45,135);
Following program uses this method to draw the face of a man and Save the file as [Link]
under Maths\applet and compile it. Create the HTML file as [Link] under Maths\applet as follows: