OOP Complete
OOP Complete
OOP Complete
LAB # 01
GETTING FAMILIAR WITH JAVA in NetBeans
Objective:
To get a hands on training exposure to the Java development environment in net beans.
Project is created.
2) EDIT CODES
Replace the line “// TODO …” with the following codes.
}
Step 3: Compile & Execute
There is no need to "compile" the source code explicitly, as NetBeans performs the so-
called incremental compilation (i.e., the source statement is compiled while it is entered).
To run the program, right-click anywhere in the source (or from the "Run" menu), select
"Run File" (or "MyConsole1un Hello.java"). Observe the output on the output console.
Notes:
You should create a new Java project for each of your Java application.
Nonetheless, NetBeans allows you to keep more than one programs in a project,
which is handy for writing toy programs (such as your tutorial exercises). If you have
more than one files with main() method in one project, you need to right-click the source
and choose "Run File".
Step 4: Read the NetBeans Documentation
At a minimum, you SHOULD READ the "IDE Basics, Getting Started, Java
Application", which is accessible via NetBeans's "HELP" menu ⇒ "Help Contents".
The "Help" ⇒ "Online Doc and Support" (@ http://netbeans.org/kb/index.html)
contains many articles and tutorial on using NetBeans.
The NetBeans "Start Page" also provides many useful links to get you started.
3. Debugging Program in NetBeans
Step 0: Write a Java Program
The following program computes and prints the factorial of n (=1*2*3*...*n). The program,
however, has a logical error and produce a wrong answer for n=20 ("The Factorial of 20 is
-2102132736" - a negative number?!).
1/** Compute the factorial of n0 */
2public class Factorial {
3 // Print factorial of n
4 public static void main(String[] args) {
5 int n = 20;
6 int factorial = 1;
7
8 // n! = 1*2*3...*n
9 for (int i = 1; i <= n; i++) {
10 factorial *= i;
11 }
12 System.out.println("The Factorial of " + n + " is " + factorial);
13 }
14}
Single-stepping thru the program and watching the values of internal variables and the
outputs produced is the ultimate mean in debugging programs - because it is exactly how the
computer runs your program!
You can modify the value of a variable by entering a new value in the "Variable" panel. This
is handy for temporarily modifying the behaviour of a program, without changing the source
code.
Step-Into and Step-Out
To debug a method, you need to use "Step-Into" to step into the first statement of the method.
You could use "Step-Out" to return back to the caller, anywhere within the method.
Alternatively, you could set a breakpoint inside a method.
command-line arguments inside the "Arguments" field ⇒ choose "Run" menu ⇒ "Run
Main Project".
12. Line Numbers: To show the line numbers, right-click on the left-margin ⇒
"Show Line Numbers".
13. Changing Font Face and Size: Tools ⇒ Options ⇒ Fonts & Colors ⇒ In
"Category", select "Default" ⇒ In "Font", choose the font face and size.
14. Resetting Window View: If you mess up the window view (e.g., you
accidentally close a window and cannot find it anymore), you can reset the view via
"Window" menu ⇒ "Reset Windows".
15. Code Templates: For example, when you create a new Java class, NetBeans
retrieves the initial contents from the "Java Class" code template. To configure code
templates, select "Tools" menu ⇒ "Templates" ⇒ Choose the desired template ⇒
"Open in Editor". To set a value of a variable used in the all the code templates
(e.g., $User), select "Tools" menu ⇒ "Templates" ⇒ "Settings".
16. Displaying Chinese Character: Need to choose a font that support chinese
character display, such as "Monospace", in Tools ⇒ Options ⇒ Fonts & Colors ⇒
Syntax ⇒ default.
17. Changing the JDK Location: The Netbeans configuration file is located at
"etc\netbeans.conf". Edit the directive "netbeans_jdkhome".
Assignment:
LAB # 02
Command Line Arguments, Data Types in java & basic
console input/output in NetBeans
Objective:
The purpose of this lab is to introduce you to the variables and the data
types, command line arguments in java and basic console input/output in net beans.
Data types in java:
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.
short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767(inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is
2 times smaller than an int
Default value is 0.
Example : short s= 10000 , short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there
is a concern about memory.
The default value is 0.
Example : int a = 100000, int b = -200000
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example : int a = 100000L, int b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point
numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example : float f1 = 234.5f
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values.
generally the default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example : double d1 = 123.4
boolean:
boolean data type represents one bit of information.
There are only two possible values : true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example : boolean >
1. char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example . char letterA ='A'
Java Literals:
A literal is a source code representation of a fixed value. They are represented
directly in the code without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10),hexadecimal(base 16) or
octal(base 8) number systems as well.
Prefix 0 is used to indicates octal and prefix 0x indicates hexadecimal when using these
number systems for literals. For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a ="\u0001";
Java language supports few special escape sequences for String and char literals as well.
They are:
Notation Character represented
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\" Double quote
\' Single quote
\\ backslash
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)
STEPS
1) START NETBEANS.
3) EDIT CODES
3-1) Replace the line “// TODO …” with the following codes.
3-3) If you hover your mouse over the red underlined text, you will get some help
message.
3-6) Run.
3-6-1) You will see the prompt “Please enter your weight:”
3-6-2) Click an area just after the colon, type 60 and press ENTER key.
3-7) Run again but this time enter “sixty” instead of a number 60.
3-10) Run.
3-13) Outcome:
Assignment:
LAB # 03
Command If Else Statements & Looping In Java
Objective:
The purpose of this lab is to introduce you to if else statement & looping in
java.
If Else Statements In Java
Instead of using two IF Statements, you can use an IF …
ELSE Statement instead. Here's the structure of an IF … ELSE statement:
if ( condition_to_test ) {
}
else {
}
The first line starts with if, followed by the condition you want to test for. This goes between
two round brackets. Again, curly brackets are used to section off the different choices. The
second choice goes after the word else and between its own curly brackets. Here's our code
again that checks a user's age:
So there are only two choices here: either the user is 18 or younger, or the user is older than
that. Adapt your code to match that in the image above and try it out. You should find that the
first message prints out. Now change the value of the user variable to 20 and run the code
again. The message between the ELSE curly brackets should display in the Output window.
you'll need to learn some more conditional operators. The ones you have used so far are
these:
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To
Here's four more you can use:
&& AND
|| OR
== HAS A VALUE OF
! NOT
The first one is two ampersand symbols, and is used to test for more than one condition at the
same time. We can use it to test for two age ranges:
else if ( user > 18 && user < 40 )
Here, we want to check if the user is older than 18 but younger than 40. Remember, we're
trying to check what is inside of the user variable. The first condition is "Greater than 18"
( user> 18 ). The second condition is "Less than 40" ( user< 40). In between the two we have
our AND operator ( &&). So the whole line says "else if user is greater than 18 AND user is
less than 40."
We'll get to the other three conditional operators in a moment. But here's some new code to
try out:
Run your program and test it out. You should be able to guess what it will print out before
running it. Because we have a value of 21 for the user variable the message between the curly
brackets of else if will display in the Output window.
Nested IF Statements
You can nest IF Statements. (This also applies to IF ... ELSE and IF ... ELSE IF statements.)
Nesting an IF Statement just means putting one IF Statement inside of another. For example,
suppose you want to find out if somebody is younger than 18, but older than 16. You want to
display a different message for the over 16s. You start with the first IF Statement:
if ( user < 19 ) {
System.out.println( "18 or younger");
}
To check for over 16, you can place a second IF Statement inside of the one you already
have. The format is the same:
if ( user < 19 ) {
if ( user > 16 && user < 19 ) {
System.out.println( "You are 17 or 18");
}}
So the first IF Statement catches the user variable if it's less than 19. The second IF Statement
narrows the user variable down even further, for ages over 16 and under 19. To print different
messages, you can have an IF ... ELSE statement instead of the IF Statement above:
Engr. Farhan Ahmed Umrani Page 19
Object Oriented Programming
if ( user < 19 ) {
if ( user > 16 && user < 19 ) {
System.out.println( "You are 17 or 18");
}
else {
System.out.println( "16 or younger");
}}
switch(wash) {
case 1: // wash is 1 for Cotton
System.out.println(“Cotton selected”);
break;
case 2: // wash is 2 for Linen
System.out.println(“Linen selected”);
break;
case 3: // wash is 3 for Wool
System.out.println(“Wool selected”);
break;
default: // Not a valid value for wash
System.out.println(“Selection error”);
break;
}
variable declaration - Initializes the variable at the beginning of the loop to some
value. This value is the starting point of the loop.
condition- Decides whether the loop will continue running or not. While this
condition is true, the loop will continue running. Once the condition becomes false,
the loop will stop running.
increment statement - The part of the loop that changes the value of the variable
created in the variable declaration part of the loop. The increment statement is the part
of the loop which will eventually stop the loop from running.
Syntax:
for(initialization; condition; increment/decrement)
{
//block of code
}
Example:
for(int a = 1; a < 11; a++)
{
System.out.print(a + " ");
}
Output:
1 2 3 4 5 6 7 8 9 10
Lets take apart the loop from the above example to see what each part does.
int a = 1- A variable named a is declared with the value of 1.
a< 11 -The condition of the loop, states that as long as the variable a is less than 11,
the loop should keep running.
a++ -The increment statement part of the loop, states that for every iteration of the
loop, the value of the variable a should increase by 1. Recall that initially a is 1.
System.out.print(a + " ")- Print the value of a together with a single space for each
time the loop runs.
The above loop will execute the code between the braces 10 times because a begins at 1 and
ends at 10. This counter is what runs the loop.
while(num< 25)
{
num = num + 5;
System.out.print(num + " ");
}
Output:
5 10 15 20 25
In the above code, a variable named num is initialized with the value of 0. The condition for
the while loop is that while num is less than 25, 5 should be added to num and it should be
printed (together with a single space). Once the value of num is greater than 25, the loop will
stop executing.
Syntax:
Do
{
//block of code
}
while (condition);
Example:
Int num = 5;
do
{
num = num + 2;
System.out.print(num + " ");
}
while (num< 25);
Output:
7 9 11 13 15 17 19 21 23
Assignment:
Write a program that makes a calculator using if else statements.
Write a program that finds factorial of odd numbers from 1 to 27 by using each of
three loops(for, while, do-while).
Write a program that finds prime numbers from 1 to 27 by using each of three
loops(for, while ,do-while).
Practice all above programs.
LAB # 04
Defining Classes
Objective:
What a class is, and how you define a class
How to define class methods
how to define & use of variable ‘this’
Defining Classes:
In this lab you’ll explore the heart of the Java language --- classes. Classes specify the objects
you use in object-oriented programming. These form the basic building blocks of any Java
program. Every program in Java involves classes, since the code for a program can appear
only within a class definition.
In essence, a class definition is very simple. There are just two kinds of things that you can
include in a class definition:
❑ Fields
These are variables that store data items that typically differentiate one object of the
class from another. They are also referred to as data members of a class.
❑ Methods
These define the operations you can perform for the class so they determine what you can do
to, or with, objects of the class. Methods typically operate on the fields—the variables of the
class.
The fields in a class definition can be of any of the primitive types, or they can be references
to objects of any class type, including the one that you are defining.
There are two kinds of fields that you can include in your classes:
The main() method, where execution of a Java application starts, must always be declared as
static, as you have seen. The reason for this should be apparent by now. Before an application
starts execution, no objects exist, so to start execution, you need a method that is executable
even though there are no objectsaround—a static method therefore.
you can do the whole thing in one step, with the following statement:
This declares the variable ball and defines the Sphere object to which it refers. You can create
another variable that refers to the same object as ball:
Sphere myBall = ball;
Now the variable myBall refers to the same object as ball. You still have only one object, but
you have two different variables that reference it. You could have as many variables as you
like referring to the same object.
Instance variables and methods can be called only using an object reference, because by
definition they relate to a particular object. The syntax is exactly the same as I have outlined
for static members. You put the name of the variable referencing the object followed by a
period, followed by the member name. To use a method volume() that has been declared as
an instance method in the Sphere class, you might write:
double ballVolume = ball.volume();
Classes
To define a class you use the keyword class followed by the name of the class, followed by a
pair of braces enclosing the details of the definition. Let’s consider a concrete example to see
how this works in practice. The definition of the Sphere class that I mentioned earlier could
be:
class Sphere
{
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Instance variables
double radius; // Radius of a sphere
*note: Whenever you want to fix the initial value that you specify for a variable—that is,
make it a constant—you just need to declare the variable with the keyword final. By
convention, constants have names in capital letters.
Defining Methods
A method is a self-contained block of code that has a name, and has the property that it is
reusable—the same method can be executed from as many different points in a program as
you require. Methods also serve to break up large and complex calculations that might
involve many lines of code into more manageable chunks.
If a method does not return a value, you can just use the keyword return by itself to end
execution of the method:
For methods that do not return a value, falling through the closing brace enclosing the body
of the method is equivalent to executing a return statement.
❑ A parameter has a name and a type and appears in the parameter list in the definition of
a
method. A parameter defines the type of value that can be passed to the method when it is
called.
❑ An argument is a value that is passed to a method when it is executed, and the value of
the argument is referenced by the parameter name during execution of the method. Of course,
the type of the argument value must be consistent with the type specified for the
corresponding parameter in the definition of the method.
class Sphere {
// Class definition as before...
// Static method to report the number of objects created
static int getCount() {
return count; // Return current object count
}
}
This method needs to be a class method because you want to be able to get at the count of the
number of objects that exist even when it is zero. You can amend the Sphere.java file to
include the definition of
getCount().
Remember that you cannot directly refer to any of the instance variables in the class
within a static method. This is because a static method can be executed when no objects
of the class have been created, and therefore no instance variables exist.
Accessing Class Data Members in a Method
An instance method can access any of the data members of the class, just by using the
appropriate name. Let’s extend the class Sphere a little further by adding a method to
calculate the volume of a Sphere object:
class Sphere
{
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Instance variables
double radius; // Radius of a sphere
double xCenter; // 3D coordinates
double yCenter; // of the center
double zCenter; // of a sphere
// Static method to report the number of objects created
static int getCount(){
return count; // Return current object count
}
// Instance method to calculate volume
double volume() {
return 4.0/3.0*PI*radius*radius*radius;
}
// Plus the rest of the class definition...
}
return 4.0/3.0*PI*this.radius*this.radius*this.radius;
For example, suppose you wanted to add a method to change the radius of a Sphere object to
a new radius value that is passed as an argument. You could code this as:
In the body of the changeRadius() method, this.radius refers to the instance variable, and
radius
by itself refers to the parameter. No confusion in the duplication of names exists here. It is
clear that you are receiving a radius value as a parameter with the name radius and storing it
in the radius variable for the class object.
Assignment:
Practice above examples of labs and attach the output of the examples.
Define a class, tkgWeight, to represent a weight in tons, kilograms, and grams, and
include a similar range of static & non static methods. Demonstrate this class by
creating and combining some class objects.
LAB # 05
Constructors
Objective:
How to define & implement class constructors
What is method overloading
How to define & implement multiple constructor
Calling a Constructor from a Constructor
Constructors
When you create an object of a class, a special kind of method called a constructor is always
invoked. If you don’t define any constructors for your class, the compiler will supply a
default constructor in the class, which does nothing. The default constructor is also
described as the no arg constructor because it requires no arguments to be specified when it
is called. The primary purpose of a constructor is to provide you with the means of
initializing the instance variables uniquely for the object that is being created.
A constructor has two special characteristics that differentiate it from other class methods:
❑ A constructor never returns a value, and you must not specify a return type not even of
type void.
❑ A constructor always has the same name as the class.
To see a practical example you could add a constructor to the Sphere class definition:
class Sphere {
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Instance variables
double radius; // Radius of a sphere
double xCenter; // 3D coordinates
double yCenter; // of the center
double zCenter; // of a sphere
// Class constructor
Sphere(double theRadius, double x, double y, double z)
{
radius = theRadius; // Set the radius
// Set the coordinates of the center
xCenter = x;
yCenter = y;
zCenter = z;
++count; // Update object count
}
// Static method to report the number of objects created
static int getCount() {
return count; // Return current object count
}
// Instance method to calculate volume
double volume() {
return 4.0/3.0*PI*radius*radius*radius;
}
}
The constructor has the same name as the class and has no return type specified. A
constructor
can have any number of parameters, including none.
Sphere()
{
}
To create an object of a class you must use the keyword new followed by a call to a
constructor. To initialize ball with a reference to an object, you could write:
you can do the whole thing in one step, with the following statement:
This declares the variable ball and defines the Sphere object to which it refers. You can create
another variable that refers to the same object as ball:
Sphere myBall = ball;
Now the variable myBall refers to the same object as ball. You still have only one object, but
you have two different variables that reference it. You could have as many variables as you
like referring to the same object.
A slight complication can arise with objects, though. As you have seen, several variables can
reference a single object. In this case, the object survives as long as a variable still exists
somewhere that references the object.
you can reset a variable to refer to nothing by setting its value to null. If you
ball = null;
class Sphere {
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Instance variables
double radius; // Radius of a sphere
double xCenter; // 3D coordinates
double yCenter; // of the center
double zCenter; // of a sphere
// Class constructor
Sphere(double theRadius, double x, double y, double z) {
radius = theRadius; // Set the radius
// Set the coordinates of the center
xCenter = x;
yCenter = y;
zCenter = z;
++count; // Update object count
}
// Static method to report the number of objects created
static int getCount() {
return count; // Return current object count
}
// Instance method to calculate volume
double volume() {
return 4.0/3.0*PI*radius*radius*radius;
}
}
Both files need to be in the same directory or folder—I suggest you name the directory
CreateSpheres. Then copy or move the latest version of Sphere.java to this directory.
Output:
Number of objects = 0
Number of objects = 1
Number of objects = 2
ball volume = 267.94666666666666
globe volume = 7234.559999999999
Method Overloading
Java allows you to define several methods in a class with the same name, as long as each
method has a unique set of parameters. Defining two or more methods with the same name in
a class is called method overloading.
The name of a method together with the types and sequence of the parameters form the
signature of the method; the signature of each method in a class must be distinct to allow the
compiler to determine exactly which method you are calling at any particular point. The
return type has no effect on the signature of a method. You cannot differentiate between two
methods just by the return type. This is because the return type is not necessarily apparent
when you call a method. For example, suppose you write a statement such as:
Math.round(value);
Multiple Constructors
Constructors are methods that can be overloaded, just like any other method in a class. In
most situations, you will want to generate objects of a class from different sets of initial
defining data.
class Sphere {
// First Constructor and variable declarations
...
// Construct a unit sphere at a point
Sphere(double x, double y, double z) {
xCenter = x;
yCenter = y;
zCenter = z;
radius = 1.0;
++count; // Update object count
}
// Construct a unit sphere at the origin
Sphere() {
xCenter = 0.0;
yCenter = 0.0;
zCenter = 0.0;
radius = 1.0;
++count; // Update object count
}
// The rest of the class as before...
}
If you add the following statements to the CreateSpheres class, you can test out the new
constructors:
public class CreateSpheres {
public static void main(String[] args) {
System.out.println(“Number of objects = “ + Sphere.getCount());
Sphere ball = new Sphere(4.0, 0.0, 0.0, 0.0); // Create a sphere
System.out.println(“Number of objects = “ + ball.getCount());
Sphere globe = new Sphere(12.0, 1.0, 1.0, 1.0); // Create a sphere
System.out.println(“Number of objects = “ + Sphere.getCount());
Sphere eightBall = new Sphere(10.0, 10.0, 0.0);
Sphere oddBall = new Sphere();
System.out.println(“Number of objects = “ + Sphere.getCount());
// Output the volume of each sphere
System.out.println(“ball volume = “ + ball.volume());
System.out.println(“globe volume = “ + globe.volume());
System.out.println(“eightBall volume = “ + eightBall.volume());
System.out.println(“oddBall volume = “ + oddBall.volume());
}
}
Output:
Number of objects = 0
Number of objects = 1
Number of objects = 2
Number of objects = 4
ball volume = 267.94666666666666
globe volume = 7234.559999999999
eightBall volume = 4.1866666666666665
oddBall volume = 4.1866666666666665
Calling a Constructor from a Constructor
One class constructor can call another constructor in the same class in its first executable
statement. This can often save duplicating a lot of code. To refer to another constructor in the
same class, you use this as the method name, followed by the appropriate arguments between
parentheses. In the Sphere class, you could have defined the constructors as:
class Sphere {
// Construct a unit sphere at the origin
Sphere() {
radius = 1.0;
// Other data members will be zero by default
++count; // Update object count
}
// Construct a unit sphere at a point
Sphere(double x, double y, double z)
{
this(); // Call the constructor with no arguments
xCenter = x;
yCenter = y;
zCenter = z;
}
Sphere(double theRadius, double x, double y, double z) {
this(x, y, z); // Call the 3 argument constructor
radius = theRadius; // Set the radius
}
// The rest of the class as before...
}
Using Objects
class Point {
// Coordinates of the point
double x;
double y;
// Create a point from coordinates
Point(double xVal, double yVal) {
x = xVal;
y = yVal;
}
// Create a point from another Point object
Point(final Point oldPoint) {
x = oldPoint.x; // Copy x coordinate
y = oldPoint.y; // Copy y coordinate
}
// Move a point
void move(double xDelta, double yDelta) {
// Parameter values are increments to the current coordinates
x += xDelta;
y += yDelta;
}
// Calculate the distance to another point
double distance(final Point aPoint) {
return sqrt((x – aPoint.x)*(x – aPoint.x) + (y – aPoint.y)*(y – aPoint.y));
}
// Convert a point to a string
public String toString() {
return Double.toString(x) + “, “ + y; // As “x, y”
}
}
class Line
{
Point start; // Start point of line
Point end; // End point of line
// Create a line from two points
Line(final Point start, final Point end) {
this.start = new Point(start);
this.end = new Point(end);
}
// Create a line from two coordinate pairs
Line(double xStart, double yStart, double xEnd, double yEnd) {
start = new Point(xStart, yStart); // Create the start point
end = new Point(xEnd, yEnd); // Create the end point
}
// Calculate the length of a line
double length() {
return start.distance(end); // Use the method from the Point class
}
// Convert a line to a string
public String toString() {
return “(“ + start+ “):(“ + end + “)”; // As “(start):(end)”
} // that is, “(x1, y1):(x2, y2)”
}
*) Calculating Powers
Here is the complete program, including the recursive method power():
Assignment:
Practice the above programs.
LAB # 06
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.
There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...
A final variable that is not initialized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output:70
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }
If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
Output:Compile Time Error
Understanding Packages:
Packages are implicit in the organization of the standard classes as well as your own
programs, and they influence the names you can use for classes and the variables and
methods they contain. Essentially, a package is a uniquely named collection of classes. The
primary reason for grouping classes in packages is to avoid possible name clashes with your
own classes when you are using prewritten classes in an application. The names used for
classes in one package will not interfere with the names of classes in another package or your
program because the class names in a package are all qualified by the package name. Thus,
the String class you have been using is in the java.lang package, so the full name of the class
is java.lang.String. You have been able to use the unqualified name because all the classes in
the java.lang package are always available in your program code; there’s an implicit import
statement in effect for all the names in the java.lang package.
The keyword import is followed by the specification of what you want to import. The
wildcard *, following the period after the package name, selects all the classes in the package,
rather like selecting all the files in a directory. Now you can refer to any public class in the
package just by using the class name.
If you want to add a particular class rather than an entire package, you specify its name
explicitly in the import statement:
Note that the * can be used only to select all the classes in a package. You can’t use
Geometry.* to select all the packages in the Geometry directory.
You can remove the need for prefixing PI with the Math class name by importing the PI
member name from the Math class:
Within a package such as package1 only the private members of the class Class1 can’t be
directly accessed by methods in other classes in the same package. If you declare a class
member to be private, it can be accessed only by methods in the same class.
As I said earlier, a class definition must have an access attribute of public if it is to be
accessible from outside the package that contains it. The above figure shows the situation
where the classes seeking access to the members of a public class are in different packages.
Here access is more restricted. The only members of Class1 that can be accessed from an
ordinary class, Class2, in another package, are those specified as public. Keep in mind that
the class Class1 must also have been defined with the attribute public for this to be the case.
A class that is not defined as public cannot be accessed at all from a class in another package.
From a subclass of Class1 that is in another package, the members of Class1 without an
access attribute cannot be reached, and neither can the private members—these can never be
accessed externally under any circumstances.
Assignment:
Make two classes name tkgWeight & mcmLength, put both the classes in a package
called Measures. Import this package into a program that will calculate and display
the total weight of the following: 200 carpets—size: 4 meters by 2 meters 9
centimeters, that weigh 1.25 kilograms per square meter; and 60 carpets—size: 3
meters 57 centimeters by 5 meters, that weight 1.05 kilograms per square meter.
LAB # 07
Nested Classes
Objective:
How to define & use nested classes.
How to define & use Static & Non-static Nested Classes
The concept of local nested classes, The finalize() Method & Native
Methods.
How to define & use recursive method
Nested Classes:
All the classes you have defined so far have been separate from each other each stored away
in its own source file. Not all classes have to be defined like this. You can put the definition
of one class inside the definition of another class. The inside class is called a nested class. A
nested class can itself have another class nested inside it, if need be.
When you define a nested class, it is a member of the enclosing class in much the same way
as the other class members. A nested class can have an access attribute just like other class
members, and the accessibility from outside the enclosing class is determined by the
attributes in the same way:
No objects of the nested class, Inside, are created. If you now wish to create an object of the
type of the nested class, you must refer to the nested class type using the name of the
enclosing class as a qualifier.
For instance, having declared an object of type Outside, you can create an object of type
Inside as follows:
Within nonstatic methods that are members of Outside, you can use the class name Inside
without any qualification, as it will be automatically qualified by the compiler with the this
variable. So you could create a new Inside object from within the method of the object
Outside:
Now with Skinside inside Outside declared as static, you can declare objects of this nested
class
type independent from any objects of type Outside, and regardless of whether you have
created any Outside objects or not. For example:
Note that a static nested class can have static members, whereas a non-static nested class
cannot. A class containing both a static and a non-static nested class is illustrated in Figure
below.
Here’s what you need to add for the Rabbit class definition:
Note that the constructor in the Rabbit class can access the select member of the enclosing
class,
MagicHat, without qualification. This is possible only with static members of the enclosing
class you can’t refer to non-static members of the enclosing class here because there is no
object of type MagicHat associated with it.
You can use the following application class to try out the nested class:
The answer is to keep rabbitNames and rabbitNamesCount as static, but put them in the
MagicHat class instead. Let’s see that working.
public Rabbit() {
int index = select.nextInt(rabbitNames.length); // Get random name index
name = rabbitNames[index] + (++rabbitNamesCount[index]);
}
// String representation of a rabbit
public String toString() {
return name;
}
}
}
This method is useful if your class objects use resources that require some special action
when they are destroyed. Typically these are resources that are not within the Java
environment and not guaranteed to be released by the object itself. These could be such
things as graphics resources, fonts or other drawing related resources that are supplied by the
host operating system, or external files on the hard disk.
Leaving these around after an object is destroyed wastes system resources and, in some
circumstances (with graphics resources under some older versions of Windows, for example)
if you waste enough of them, your program, and possibly other programs the system is
supporting, may stop working. For most classes this is not necessary, but if an object opened
a disk file for example, but did not guarantee its closure, you would want to make sure that
the file was closed when the object was destroyed. You can implement the finalize() method
to take care of this.
The System class also provides another possible approach. You can suggest to the JVM that
the
finalize() methods for all discarded objects should be run, if they haven’t been already. You
just
call the runFinalization() method:
System.runFinalization();
This is another of those “best efforts” deals on the part of the JVM. It will do its very best to
run
finalize() for any dead objects that are lying around before returning from the
runFinalization() method, but like with a lot of things in this life, there are no guarantees.
Native Methods:
It is possible to include in a class a method that is implemented in some other programming
language, such as C or C++, external to the Java Virtual Machine. To specify such a method
within a class definition, you use the keyword native in the declaration of the method. For
example:
Of course, the method will have no body in Java since it is defined elsewhere, where all the
work is done, so the declaration ends with a semicolon. The implementation of a native
method will need to use an interface to the Java environment. The standard API for
implementing native methods in C, for example, is called JNI—the Java Native Interface.The
major drawback to using native methods in Java is that your program will no longer be
portable. Security requirements for applets embedded in web pages require that the code must
all be written in Java—using native methods in an applet is simply not possible.
Recursion:
The methods you have seen so far have been called from within other methods, but a method
can also call itself. A method that calls itself is described as a recursive method, and the
process is referred to as recursion. You can also have indirect recursion where a method A
calls another method B, which in turn calls the method A. Clearly you must include some
logic in a recursive method so that it will eventually stop calling itself if the process is not to
continue indefinitely. You can see how this might be done with a simple example.
Calculating Powers
Here is the complete program, including the recursive method power():
public class PowerCalc {
public static void main(String[] args) {
double x = 5.0;
System.out.println(x + “ to the power 4 is “ + power(x,4));
System.out.println(“7.5 to the power 5 is “ + power(7.5,5));
Engr. Farhan Ahmed Umrani Page 57
Object Oriented Programming
Assignment:
Practice all above program and take snapshot of it.
Make a program in which you calculate the price of goods present in the shop. Take
input price and quantity and give result for three sizes big, medium & small. Define a
class ‘price’, to represent outer class, make static inner class named ‘small’, make
another inner classes named ‘big’ & ‘medium’.
Make a program in which recursive method is used and you must include some logic
in a recursive method so that it will eventually stop calling itself if the process is not
to continue indefinitely.
LAB # 08
Extending Classes and Inheritance
Objective:
How to use existing classes and accessibility of inheriting data members
& methods.
How to hide data members & methods of base class.
How to use constructor of base class in a derived class.
How to override a Base Class Method in a derived class.
How to call a base class method & data members from a derived class.
Let’s start by understanding the jargon. Defining a new class based on an existing class is
called
derivation. The new class, or derived class, is referred to as a direct subclass of the class
from
which it is derived. The original class is called a base class because it forms the base for the
definition of the derived class. The original class is also referred to as a superclass of the
derived class. You can also derive a new class from a derived class, which in turn was
derived from some other derived class, and so on.
The above figure shows just three classes in a hierarchy, but there can be as many as you like.
Let’s consider a more concrete example. You could define a class Dog that could represent a
dog of any kind:
class Dog
{
// Members of the Dog class...
}
This might contain a data member identifying the name of a particular dog, such as Lassie or
Poochy, and another data member to identify the breed, such as Border Collie or Pyrenean
Mountain Dog. From the Dog class, you could derive a Spaniel class that represented dogs
that were spaniels:
The extends keyword that you use here identifies that Dog is a base class for Spaniel, so an
object of type Spaniel will have members that are inherited from the Dog class, in addition to
the members of the Spaniel class that appear in its definition.
A Spaniel object is a specialized instance of a Dog object. This reflects real life. A spaniel is
obviously a dog and will have all the properties of a basic dog, but it has some unique
characteristics of its own that distinguish it from all the dogs that are not spaniels. The
inheritance mechanism that adds all the properties of the base class—Dog in this instance—to
those in the derived class is a good model for the real world. The members of the derived
class define the properties that differentiate it from the base type, so when you derive one
class from another, you can think of your derived class as a specification for objects that are
specializations of the base class object. Another way of thinking about this is that the base
class defines a set of objects and a derived class defines a specific subset of those that have
particular defining characteristics.
Class Inheritance:
The inclusion of members of a base class in a derived class so that they are accessible in that
derived class is called class inheritance. An inherited member of a base class is one that is
accessible within the derived class. If a base class member is not accessible in a derived class,
then it is not an inherited member of the derived class, but base class members that are not
inherited still form part of a derived class object.
Inheriting Data Members:
Remember that inheritance implies accessibility of the member in a derived class, not just
presence.
Remember that a class itself can be specified as public. This makes the class accessible
from any package anywhere. A class that is not declared as public can be accessed only
from classes within the same package. This means, for example, that you cannot define
objects of a non-public class type within classes in other packages. It also means that to
derive a new class from a class in a different package, the base class must be declared as
public. If the base class is not declared as public, it cannot be reached directly from
outside the package.
*Note that you cannot use super.super.something to refer to a member name hidden in
the base class of a base class.
Inherited Methods:
Ordinary methods in a base class, by which I mean methods that are not constructors, are
inherited in a derived class in the same way as the data members of the base class. Those
methods declared as private in a base class are not inherited, and those that you declare
without an access attribute are inherited only if you define the derived class in the same
package as the base class. The rest are all inherited. Constructors are different from ordinary
methods. Constructors in the base class are never inherited, regardless of their
attributes.
Deriving a Class:
Let’s take a simple example. Suppose you have defined a class to represent an animal as
follows:
public class Animal
{
public Animal(String aType)
{
type = new String(aType);
}
public String toString()
{
return “This is a “ + type;
}
private String type;
}
This has a member, type, to identify the type of animal, and its value is set by the constructor.
You also have a toString() method for the class to generate a string representation of an
object of the class. You can now define another class, based on the class Animal, to define
dogs. You can do this immediately, without affecting the definition of the class Animal. You
could write the basic definition of the class Dog as:
You use the keyword extends in the definition of a subclass to identify the name of the direct
superclass. The class Dog will inherit only the method toString() from the class Animal, since
the private data member and the constructor cannot be inherited. Of course, a Dog object will
have a type data member that needs to be set to “Dog”, it just can’t be accessed by methods
that you define in the Dog class. You have added two new instance variables in the derived
class. The name member holds the name of the particular dog, and the breed member records
the kind of dog it is. All you need to add is the means of creating Dog class objects.
}
private String name; // Name of a Dog
private String breed; // Dog breed
}
The statement in the derived class constructors that calls the base class constructor is:
super(“Dog”); // Call the base constructor
You can add the definition of a new version of toString() to the definition of the derived
class, Dog:
Assignment:
Practice all above programs.
Define a class fruit as base class, define more classes apple, mango, strawberry as
derive classes. define method juice in base class and override it in derived class also
call base class method from derived class by using super keyword, make constructor
in base class and initialize it properly through derived class constructor. Use super
keyword in derived class for calling base class constructor.
Define a class, ShapeList, that can store collection of any objects of subclasses of the
Shape class.
LAB # 09
Polymorphism
Objective:
How to apply polymorphism in the program.
How to define & use multiple level of inheritance.
Polymorphism:
The word polymorphism generally means the ability to assume several different forms or
shapes. In programming terms it means the ability of a single variable of a given type to be
used to reference objects of different types and to automatically call the method that is
specific to the type of object the variable references. This enables a single method call to
behave differently, depending on the type of the object to which the call applies.
Polymorphism means that the actual type of the object involved in a method call determines
which method is called, rather than the type of the variable being used to store the reference
to the object. In Figure 6-4, if aDog contains a reference to a Spaniel object, the bark()
method for that object will be called. If it contains a reference to a Collie object, the bark()
method in the Collie class will be called.
You can redefine the createCreature() method in a derived class Dog like this:
I can summarize the conditions that need to be met if you want to use polymorphism as
follows:
❑ The method call for a derived class object must be through a variable of a base class type.
❑ The method called must be defined in the derived class.
❑ The method called must also be declared as a member of the base class.
❑ The method signatures for the method in the base and derived classes must be the same.
❑ Either the method return type must be the same in the base and derived classes or the
return
type must be covariant.
❑ The method access specifier must be no more restrictive in the derived class than in the
base.
Using Polymorphism:
Enhancing the Dog Class
First of all you will enhance the class Dog by adding a method to display the sound that a dog
makes:
You can also derive a class Cat from the class Animal:
You need to make one change to the class Animal. To select the method sound() dynamically
for derived class objects, it needs to be a member of the base class. You can add a content-
free version of sound() to the class Animal:
class Animal {
Only a particular Animal object will make a specific sound, so the sound() method in the
class does nothing. You need a program that will use these classes. To give the classes a
workout, you can create an array of type Animal and populate its elements with different
subclass objects. You can then select an object random from the array, so that there is no
possibility that the type of the object selected is known ahead of time. Here’s the code to do
that:
import java.util.Random;
Animal[] theAnimals = {
new Duck(“Daffy”,”Aylesbury”)
};
petChoice = theAnimals[select.nextInt(theAnimals.length)];
Your choice:
This is a Duck
It’s Daffy the Aylesbury
Quack quackquack
Your choice:
This is a Cat
It’s Max the Abyssinian
Miiaooww
Your choice:
This is a Duck
It’s Daffy the Aylesbury
Quack quackquack
Your choice:
This is a Duck
It’s Daffy the Aylesbury
Quack quackquack
Your choice:
This is a Cat
It’s Max the Abyssinian
Miiaooww
The chances are good that you will get a different set from this, and a different set again
when you rerun the example.
Multiple Levels of Inheritance
As I indicated at the beginning of the chapter, there is nothing to prevent a derived class from
being used as a base class. For example, you could derive a class Spaniel from the class Dog
without any problem:
A Spaniel Class
Start the Spaniel class off with this minimal code:
class Spaniel extends Dog {
public Spaniel(String aName) {
super(aName, “Spaniel”);
}
}
To try this out you can add a Spaniel object to the array theAnimals in the previous example,
by
changing the statement to:
Animal[] theAnimals = {
new Dog(“Rover”, “Poodle”),
new Cat(“Max”, “Abyssinian”),
new Duck(“Daffy”,”Aylesbury”),
new Spaniel(“Fido”)
};
Don’t forget to add in the comma after the Duck object. Try running the example again a few
times.
Assignment:
Practice all above programs.
LAB # 10
Abstract Classes
Objective:
How to make & use abstract class in the program.
Abstract Classes:
In the Animal class, you introduced a version of the sound() method that did nothing because
you wanted to call the sound() method in the subclass objects dynamically. The method
sound() has no meaning in the context of the generic class Animal, so implementing it does
not make much sense. This situation often arises in object-oriented programming. You will
often find yourself creating a super class from which you will derive a number of subclasses,
just to take advantage of polymorphism. To cater for this, Java has abstract classes. An
abstract class is a class in which one or more methods are declared, but not defined. The
bodies of these methods are omitted, because, as in the case of the method sound() in the
Animal class, implementing the methods does not make sense. Since they have no definition
and cannot be executed, they are called abstract methods. The declaration for an abstract
method ends with a semicolon and you specify the method with the keyword abstract to
identify it as such. To declare that a class is abstract you just use the keyword abstract in front
of the class keyword in the first line of the class definition. You could have defined the class
Animal as an abstract class by amending it as follows:
The previous program will work just as well with these changes. It doesn’t matter whether
you prefix the class name with public abstract or abstract public, they are equivalent, but you
should be consistent in your usage. The sequence public abstract is typically preferred. The
same goes for the declaration of an abstract method, but both public and abstract must
precede the return type specification, which is void in this case.
An abstract method cannot be private since a private method cannot be inherited and
therefore cannot be redefined in a subclass. You cannot instantiate an object of an abstract
class, but you can declare a variable of an abstract class type. With the new abstract version
of the class Animal, you can still write:
just as you did in the TryPolymorphism class. You can then use this variable to store objects
of the subclasses,
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
obj.run();
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.
//In real scenario, implementation is provided by others i.e. unknown by end user
class TestAbstraction1{
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape()
method
s.draw();
class TestBank{
Bank b;
b=new SBI();
b=new PNB();
Bike(){System.out.println("bike is created");}
class TestAbstraction2{
obj.run();
obj.changeGear();
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Output
Rule: If you are extending any abstract class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
Note that getClass(), notify(), notifyAll(), and wait() cannot be overridden in your own class
definitions—they are fixed with the keyword final in the class definition for Object (see the
section on the final modifier later in this chapter). It should be clear now why you could get
polymorphic behavior with toString() in your derived classes when your base class did not
define the method. There is always a toString() method in all your classes that is inherited
from Object.
The two protected methods that your classes inherit from Object are:
Since all your classes will inherit the methods defined in the Object class you should look at
them in a little more detail.
Casting Objects
You can cast an object to another class type, but only if the current object type and the new
class type are in the same hierarchy of derived classes, and one is a superclass of the other.
For example, in earlier labs you defined the classes Animal, Dog, Spaniel, Cat, and Duck,
and these classes are related in the hierarchy. You can cast a reference to an object of a class
upwards through its direct and indirect superclasses. For example, you could cast a reference
to an object of type Spaniel directly to type Dog, type Animal, or type Object. You could
write:
When you are assigning an object reference to a variable of a superclass type, you do not
have to include the cast. You could write the assignment as:
This would work just as well. The compiler is always prepared to insert a cast to a superclass
type when necessary.
Assignment:
Practice all above programs and take snapshot of outputs.
Define an abstract base class Shape that includes protected data members for the (x, y)
position of a shape, a public method to move a shape, and a public abstract method
show() to output a shape. Derive subclasses for lines, circles, and rectangles. You can
represent a line as two points, a circle as a center and a radius, and a rectangle as two
points on diagonally opposite corners. Implement the toString() method for each
class. Test the classes by selecting ten random objects of the derived classes, and then
invoking the show() method for each. Use the toString() methods in the derived
classes.
LAB # 11
Interfaces:
An interface is essentially a collection of related constants and or abstract methods, and in
most cases it will contain just methods. An interface doesn’t define what a method does. It
just defines its form—its name, its parameters, and its return type, so by definition the
methods in an interface are abstract. To make use of an interface, you implement the
interface in a class—that is, you declare that the class implements the interface and you write
the code for each of the methods that the interface declares as part of the class definition.
When a class implements an interface, any constants that were defined in the interface
definition are available directly in the class, just as though they were inherited from a base
class. An interface can contain either constants, or abstract methods, or both. As below figure
illustrates, the methods in an interface are always public and abstract, so you do not need to
specify them as such; it is considered bad programming practice to specify any attributes for
them, and you definitely cannot add any attributes other than the defaults, public and abstract.
This implies that methods declared in an interface can never be static, so an interface always
declares instance methods. The constants in an interface are always public, static, and final,
so you do not need to specify the attributes for these either.
An interface is defined just like a class, but using the keyword interface rather than the
keywordclass. You store an interface definition in a .java file with the same name as the
interface. The name that you give to an interface must be different from that of any other
interface or class in the same package.
Just as for classes, the members of the interface—the constants and/or method declarations—
appear between a pair of braces that delimit the body of the interface definition.
The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public
and abstract.
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
Engr. Farhan Ahmed Umrani Page 81
Object Oriented Programming
}
Output:Hello
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Engr. Farhan Ahmed Umrani Page 82
Object Oriented Programming
Hello
Welcome
As you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance:
A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
//How Serializable interface is written?
public interface Serializable{
}
There are given some points that should be remembered by the java programmer.
o Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
o Nested interfaces are declared static implicitely.
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
In this example, we are going to learn how to declare the nested interface and how we can
access it.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7. class TestNestedInterface1 implements Showable.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. Showable.Message message=new TestNestedInterface1();//upcasting here
12. message.msg();
13. }
14. }
Test it Now
download the example of nested interface
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside the
room, we cannot access the almirah directly because we must enter the room first. In
collection frameword, sun microsystem has provided a nested interface Entry. Entry is the
subinterface of Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
1. public static interface Showable$Message
2. {
3. public abstract void msg();
4. }
Let's see how can we define an interface inside the class and how can we access it.
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class TestNestedInterface2 implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new TestNestedInterface2();//upcasting here
12. message.msg();
13. }
14. }
Test it Now
Output:hello nested interface
Yes, If we define a class inside the interface, java compiler creates a static nested class. Let's
see how can we define a class within the interface:
1. interface M{
2. class A{}
3. }
Assignment:
Practice all above programs and take snapshot of outputs.
Define a class shape and three interfaces respective to the class; implement all three
interfaces in the class.
LAB # 12
Enumerations & Encapsulation
Objective:
How to make & use Enumeration in java programs.
How to make & use Encapsulation in java programs.
Enumerations
An enumeration type is a special form of class. When you define an enumeration type in your
code, the enumeration constants that you specify are created as instances of a class that has
the Enum class, which is defined in the java.lang package, as a superclass. The object that
corresponds to each enumeration constant stores the name of the constant in a field, and the
enumeration class type inherits the toString method from the Enum class. The toString()
method in the Enum class returns the original name of the enumeration constant, so that’s
why you get the name you gave to an enumeration constant displayed when you output it
using the println() method. You have seen that you can put the definition of an enumeration
type within the definition of a class. You can also put the definition is a separate source file.
In this case you specify the name of the file containing the enumeration type definition in the
same way as for any other class type. An enumeration that you define in its own source file
can be accessed by any other source file in exactly the same way as any other class definition.
An object representing an enumeration constant also stores an integer field. By default, each
constant in an enumeration will be assigned an integer value that is different from all the
other constants in the enumeration. The values are assigned to the enumeration constants in
the sequence in which you specify them, starting with zero for the first constant, 1 for the
second, and so on. You can retrieve the value for a constant by calling its ordinal() method,
but you should not need to do this in general.
You can compare values of an enumeration type for equality using the equals() method. For
example, assuming that you have defined an enumeration type, Season, with enumeration
constants spring, summer, fall, and winter, you could write the following:
The equals() method is inherited from the Enum class in your enumeration class type. Your
enumeration class type will also inherit the compareTo() method that compares instances of
the enumeration based on their ordinal values. It returns a negative integer if the value for the
instance for which the method is called is less than the instance that you pass as the argument,
0 if they are equal, and a positive integer if the value of the current instance is greater than the
value for the argument. Thus, the sequence in which you specify the enumeration constants
when you define them determines the order that the compareTo() method implements. You
might use it like this:
if(now.compareTo(Season.summer) > 0)
System.out.println(“It is definitely getting colder!”);
You then realize that you would really like to record the average c size applicable to each
jacket size. You could amend the definition of the enumeration like this:
constructor being callable only from inside the class. The csize is recorded in a private data
member so there is also a csize() method to allow the
value of csize to be retrieved.
Embroidering an Enumeration
First, create a new directory for the example and save the JacketSize.java file containing the
definition of the enumeration from the previous section in it. Now create another file
containing the following definition:
System.out.println(jacket);
}
}
}
When you compile and execute this program you will get the following output:
Jackets colors available are:
red orange yellow blue green
Jackets sizes available are:
small medium large extra_large extra_extra_large
Jackets in stock are:
Jacket medium in red
Jacket extra_large in yellow
Jacket small in green
Jacket extra_extra_large in blue
Encapsulation:
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will be
hidden from other classes, and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding.
Provide public setter and getter methods to modify and view the variables values.
Example:
Following is an example that demonstrates how to achieve Encapsulation in Java −
The public setXXX() and getXXX() methods are the access points of the instance variables
of the EncapTest class. Normally, these methods are referred as getters and setters.
Therefore, any class that wants to access the variables should access them through these
getters and setters.
The variables of the EncapTest class can be accessed using the following program −
Output:
Name : James Age : 20
Example:
1. //save as Student.java
2. public class Student{
3. private String name;
4.
5. public String getName(){
6. return name;
7. }
8. public void setName(String name){
9. this.name=name
10. }
11. }
1. //save as Test.java
2. class Test{
Engr. Farhan Ahmed Umrani Page 93
Object Oriented Programming
3. public static void main(String[] args){
4. Student s=new Student();
5. s.setName("vijay");
6. System.out.println(s.getName());
7. }
8. }
Output:
vijay
Benefits of Encapsulation:
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the
data type of a field and users of the class do not need to change any of their code.
Assignment:
Practice all above programs and take snapshot of outputs.
LAB # 13
Java Collections
Objective:
How to make & use of java collections in java programs.
java.util.ArrayList
java.util.LinkedList
java.util.Vector
java.util.Stack
listA.add("element 1");
listA.add("element 2");
listA.add("element 3");
The first three add() calls add a String instance to the end of the list. The last add() call
adds a String at index 0, meaning at the beginning of the list.
The order in which the elements are added to the List is stored, so you can access the
elements in the same order. You can do so using either the get(int index) method, or via
the Iterator returned by the iterator() method. Here is how:
listA.add("element 0");
listA.add("element 1");
listA.add("element 2");
When iterating the list via its Iterator or via the for-loop (which also uses the Iterator
behind the scene), the elements are iterated in the same sequence they are stored in the list.
Removing Elements
You can remove elements in two ways:
1. remove(Object element)
2. remove(int index)
remove(int index) removes the element at the given index. All subsequent elements in the
list are then moved up in the list. Their index thus decreases by 1.
Clearing a List
The Java List interface contains a clear() method which removes all elements from the list
when called. Here is simple example of clearing a List with clear():
list.add("object 1");
list.add("object 2");
//etc.
list.clear();
List Size
You can obtain the number of elements in the List by calling the size() method. Here is an
example:
list.add("object 1");
list.add("object 2");
Generic Lists
By default you can put any Object into a List, but from Java 5, Java Generics makes it
possible to limit the types of object you can insert into a List. Here is an example:
This List can now only have MyObject instances inserted into it. You can then access and
iterate its elements without casting them. Here is how it looks:
Iterating a List
You can iterate a Java List in several different ways. I will cover the three most common
mechanisms here.
The first way to iterate a List is to use an Iterator. Here is an example of iterating
a List with an Iterator:
Once you have obtained an Iterator you can keep calling its hasNext() method until it
returns false. Calling hasNext() is done inside a while loop as you can see.
If the List is typed you can save some object casting inside the while loop. Here is an
example:
Another way to iterate a List is to use the for loop added in Java 5 (also called a "for each"
loop). Here is an example of iterating a List using the for loop:
The for loop is executed once per element in the List. Inside the for loop each element is in
turn bound to the obj variable.
If the list is typed (a generic List) you can change the type of the variable inside
the for loop. Here is typed List iteration example:
Notice how the List is typed to String. Therefore you can set the type of the variable inside
the for loop to String.
The for loop creates an int variable and initializes it to 0. Then it loops as long as the int
variable i is less than the size of the list. For each iteration the variable i is incremented.
A Stack is a data structure where you add elements to the "top" of the stack, and also remove
elements from the top again. This is also referred to as the "Last In First Out (LIFO)"
principle. In contrast, a Queue uses a "First In First Out (FIFO)" principle.
stack.push("1");
stack.push("2");
stack.push("3");
Object obj3 = stack.pop(); //the string "3" is at the top of the stack.
Object obj2 = stack.pop(); //the string "2" is at the top of the stack.
Object obj1 = stack.pop(); //the string "1" is at the top of the stack.
The peek() method returns the object at the top of the Stack, but leaves the object on of
the Stack.
The pop() method returns the object at the top of the stack, and removes the object from
the Stack.
stack.push("1");
stack.push("2");
stack.push("3");
java.util.LinkedList
java.util.PriorityQueue
PriorityQueue stores its elements internally according to their natural order (if they
implement Comparable), or according to a Comparator passed to the PriorityQueue.
queueA.add("element 1");
queueA.add("element 2");
queueA.add("element 3");
The order in which the elements added to the Queue are stored internally, depends on the
implementation. The same is true for the order in which elements are retrieved from the
queue. You should consult the JavaDoc's for more information about the
specific Queue implementations.
You can peek at the element at the head of the queue without taking the element out of the
queue. This is done via the element() method. Here is how that looks:
To take the first element out of the queue, you use the remove() method which is described
later.
You can also iterate all elements of a queue, instead of just processing one at a time. Here is
how that looks:
queueA.add("element 0");
queueA.add("element 1");
queueA.add("element 2");
while(iterator.hasNext(){
When iterating the queue via its Iterator or via the for-loop (which also uses the Iterator
behind the scene, the sequence in which the elements are iterated depends on the queue
implementation.
Removing Elements
To remove elements from a queue, you call the remove() method. This method removes the
element at the head of the queue. In most Queue implementations the head and tail of the
queue are at opposite ends. It is possible, however, to implement the Queue interface so that
the head and tail of the queue is in the same end. In that case you would have a stack.
Generic Queue
By default you can put any Object into a Queue, but from Java 5, Java Generics makes it
possible to limit the types of object you can insert into a Queue. Here is an example:
This Queue can now only have MyObject instances inserted into it. You can then access and
iterate its elements without casting them. Here is how it looks:
Assignment:
Practice all above programs and take snapshot of outputs.
LAB # 14
Threading in Java
Objective:
How to make & use of thread in java programs.
Thread in java:
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation
of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
Output:thread is running...
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }
Output:thread is running...
If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.
There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task executes
for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then
determines which task should execute next, based on priority and other factors.
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on
1. public class TestThreadTwice1 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestThreadTwice1 t1=new TestThreadTwice1();
7. t1.start();
8. t1.start();
9. }
10. }
Test it Now
running
Exception in thread "main" java.lang.IllegalThreadStateException
1. class TestCallRun1 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestCallRun1 t1=new TestCallRun1();
7. t1.run();//fine, but does not start a separate call stack
8. }
9. }
Test it Now
Output:running...
1. class TestCallRun2 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestCallRun2 t1=new TestCallRun2();
10. TestCallRun2 t2=new TestCallRun2();
11.
12. t1.run();
13. t2.run();
14. }
15. }
Test it Now
Output:1
2
3
4
5
1
2
3
4
5
Engr. Farhan Ahmed Umrani Page 113
Object Oriented Programming
As you can see in the above program that there is no context-switching because here t1
and t2 will be treated as normal object not thread object.
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
Each process have its own address in memory i.e. each process allocates separate
memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
Assignment:
Practice all above programs and take snapshot of outputs.
LAB # 15
Exception Handling in Java
Objective:
How to handle exception in java programs.
In this page, we will learn about java exception, its type and the difference between checked
and unchecked exceptions.
What is exception?
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5,
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform
exception handling, rest of the statement will be executed. That is why we use exception
handling in java.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
try{
//code that may throw exception
}finally{}
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Test it Now
Output:
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
1. public class Testtrycatch2{
2. public static void main(String args[]){
3. try{
4. int data=50/0;
5. }catch(ArithmeticException e){System.out.println(e);}
6. System.out.println("rest of the code...");
7. }
8. }
Test it Now
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
1. public class TestMultipleCatchBlock{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed
");}
9. catch(Exception e){System.out.println("common task completed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Test it Now
Output:task1 completed
rest of the code...
Rule: At a time only one Exception is occured and at a time only one catch block is
executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
1. class TestMultipleCatchBlock1{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed
");}
10. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Compile-time error
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. }
19. }
Assignment:
Practice all above programs and take snapshot of outputs.
LAB # 16
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
any).
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:5
finally block is always executed
rest of the code...
Case 2
12. Let's see the java finally example where exception occurs and not handled.
13. class TestFinallyBlock1{
14. public static void main(String args[]){
15. try{
16. int data=25/0;
1. System.out.println(data);
2. }
3. catch(NullPointerException e){System.out.println(e);}
4. finally{System.out.println("finally block is always executed");}
5. System.out.println("rest of the code...");
6. }
7. }
Test it Now
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit()
or by causing a fatal error that causes the process to abort).
1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Test it Now
Output:exception handled
normal flow...
In the above example exception occurs in m() method where it is not handled,so it is
propagated to previous n() method where it is not handled, again it is propagated to p()
method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p()
method,n() method or m() method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
Engr. Farhan Ahmed Umrani Page 130
Object Oriented Programming
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
Test it Now
1) Rule: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild extends Parent{
7. void msg()throws IOException{
8. System.out.println("TestExceptionChild");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild();
12. p.msg();
13. }
14. }
Test it Now
Output:Compile Time Error
2) Rule: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but can declare unchecked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild1 extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild1();
12. p.msg();
13. }
14. }
Test it Now
Output:child
1) Rule: If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent exception.
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild2 extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild2();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:Compile Time Error
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild3 extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild3();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:child
Engr. Farhan Ahmed Umrani Page 133
Object Oriented Programming
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild4 extends Parent{
7. void msg()throws ArithmeticException{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild4();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:child
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild5 extends Parent{
7. void msg(){System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild5();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:child
By the help of custom exception, you can have your own exception and message.
1. class InvalidAgeException extends Exception{
2. InvalidAgeException(String s){
3. super(s);
4. }
5. }
1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured: "+m);}
14.
15. System.out.println("rest of the code...");
16. }
17. }
Test it Now
Engr. Farhan Ahmed Umrani Page 135
Object Oriented Programming
Assignment:
Practice all above programs and take snapshot of outputs.
Note: The above topics are not included in lab manual but all these topics
can be covered by presentation or by home assignment.
Contents
To complete this tutorial, you need the following software and resources.
Software or Resource Version Required
2. In the Categories pane, select the Java node. In the Projects pane, choose Java Application. Click Next.
3. Type NumberAddition in the Project Name field and specify a path, for example, in your home
directory, as the project location.
4. (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify the location for
the libraries folder. See Sharing a Library with Other Users in Developing Applications with NetBeans
IDE for more information.
5. Deselect the Create Main Class checkbox if it is selected.
6. Click Finish.
2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form file
type. Click Next.
5. Click Finish.
The IDE creates the NumberAdditionUI form and the NumberAdditionUI class within
the NumberAddition application, and opens the NumberAdditionUI form in the GUI Builder.
The my.NumberAddition package replaces the default package.
Adding Components: Making the Front End
Next we will use the Palette to populate our application's front end with a JPanel. Then we will add three JLabels,
three JTextFields, and three JButtons. If you have not used the GUI Builder before, you might find information in
the Designing a Swing GUI in NetBeans IDE tutorial on positioning components useful.
Once you are done dragging and positioning the aforementioned components, the JFrame should look
something like the following screenshot.
If you do not see the Palette window in the upper right corner of the IDE, choose Window > Palette.
1. Start by selecting a Panel from the Swing Containers category on Palette and drop it onto the JFrame.
2. While the JPanel is highlighted, go to the Properties window and click the ellipsis (...) button next to
Border to choose a border style.
3. In the Border dialog, select TitledBorder from the list, and type in Number Addition in the Title field.
Click OK to save the changes and exit the dialog.
4. You should now see an empty titled JFrame that says Number Addition like in the screenshot. Look at
the screenshot and add three JLabels, three JTextFields and three JButtons as you see above.
4. Delete the sample text from jTextField1. You can make the display text editable by right-clicking
the text field and choosing Edit Text from the popup menu. You may have to resize
the jTextField1 to its original size. Repeat this step for jTextField2 and jTextField3.
5. Rename the display text of jButton1 to Clear. (You can edit a button's text by right-clicking the
button and choosing Edit Text. Or you can click the button, pause, and then click again.)
6. Rename the display text of jButton2 to Add.
Your Finished GUI should now look like the following screenshot:
4. You can have your application respond to key presses, single, double and triple mouse clicks, mouse
motion, window size and focus changes. You can generate event handlers for all of them from the
Events menu. The most common event you will use is an Action event. (Learn best practices for Event
handling from Sun's Java Events Tutorial.)
How does event handling work? Every time you select an event from the Event menu, the IDE automatically
creates a so-called event listener for you, and hooks it up to your component. Go through the following steps to
see how event handling works.
1. Go back to the file NumberAdditionUI.java in the Editor. Click the Source tab to see the GUI's
source.
2. Scroll down and note the
methods jButton1ActionPerformed(), jButton2ActionPerformed(),
and jButton3ActionPerformed() that you just implemented. These methods are called event
handlers.
3. Now scroll to a method called initComponents(). If you do not see this method, look for a line that
says Generated Code; click the + sign next to it to expand the
collapsed initComponents()method.
4. First, note the blue block around the initComponents() method. This code was auto-generated by
the IDE and you cannot edit it.
5. Now, browse through the initComponents() method. Among other things, it contains the code that
initializes and places your GUI components on the form. This code is generated and updated
automatically while you place and edit components in the Design view.
6. In initComponents(), scroll down to where it reads
7. jButton3.setText("Exit");
8. jButton3.addActionListener(new java.awt.event.ActionListener() {
9. public void actionPerformed(java.awt.event.ActionEvent evt) {
10. jButton3ActionPerformed(evt);
11. }
});
This is the spot where an event listener object is added to the GUI component; in this case, you register
an ActionListener to the jButton3. The ActionListener interface has an actionPerformed method
This tutorial guides you through the process of creating the graphical user interface (GUI) for an application
called ContactEditor using the NetBeans IDE GUI Builder. In the process you will layout a GUI front-end that
enables you to view and edit contact information of individuals included in an employee database.
In this tutorial you will learn how to: use the GUI Builder Interface, create a GUI Container, add, resize, and align
components, adjust component anchoring, set component auto-resizing behavior, edit component properties.
Contents
Getting Started
Creating a Project
Creating a JFrame Container
Getting Familiar with the GUI Builder
Key Concepts
Free Design
Automatic Component Positioning (Snapping)
Visual Feedback
First Things First
Adding Components: The Basics
Adding Individual Components to the Form
Adding Multiple Components to the Form
Inserting Components
Moving Forward
Component Alignment
Baseline Alignment
Reviewing What We've Learned
Adding, Aligning, and Anchoring
Component Sizing
Indentation
Making the Final Adjustments
Previewing Your GUI
Deploying GUI Applications
See Also
To complete this tutorial, you need the following software and resources.
Software or Resource Version Required
Getting Started
The IDE's GUI Builder makes it possible to build professional-looking GUIs without an intimate understanding of
layout managers. You can lay out your forms by simply placing components where you want them.
For descriptions of the GUI Builder's visual feedback, you can use the GUI Builder Visual Feedback Legend.
Creating a Project
Because all Java development in the IDE takes place within projects, we first need to create a
new ContactEditor project within which to store sources and other project files. An IDE project is a group of
Java source files plus its associated meta data, including project-specific properties files, an Ant build script that
controls the build and run settings, and a project.xml file that maps Ant targets to IDE commands. While
Java applications often consist of several IDE projects, for the purposes of this tutorial, we will build a simple
application which is stored entirely in a single project.
2. In the Categories pane, select the Java node and in the Projects
pane, choose Java Application. Click Next.
3. Enter ContactEditor in the Project Name field and specify the
project location.
4. Leave the Use Dedicated Folder for Storing Libraries checkbox
unselected.
5. Ensure that the Set as Main Project checkbox is selected and clear
the Create Main Class field.
6. Click Finish.
The IDE creates the ContactEditor folder on your system in the
designated location. This folder contains all of the project's associated
files, including its Ant script, folders for storing sources and tests, and
a folder for project-specific metadata. To view the project structure,
use the IDE's Files window.
Creating a JFrame Container
After creating the new application, you may have noticed that the Source Packages folder in the Projects window
contains an empty <default package> node. To proceed with building our interface, we need to create a
Java container within which we will place the other required GUI components. In this step we'll create a container
using the JFrame component and place the container in a new package.
To add a JFrame container:
1. In the Projects window, right-click the ContactEditor node and
choose New > JFrame Form.
Alternatively, you can find a JFrame form by choosing New > Other >
Swing GUI Forms > JFrame Form.
2. Enter ContactEditorUI as the Class Name.
3. Enter my.contacteditor as the package.
4. Click Finish.
The IDE creates the ContactEditorUI form and
the ContactEditorUI class within
the ContactEditorUI.java application and opens
the ContactEditorUI form in the GUI Builder. Notice that
the my.contacteditor package replaces the default package.
When we added the JFrame container, the IDE opened the newly-created ContactEditorUI form in an
Editor tab with a toolbar containing several buttons, as shown in the preceding illustration. The ContactEditor
form opened in the GUI Builder's Design view and three additional windows appeared automatically along the
IDE's edges, enabling you to navigate, organize, and edit GUI forms as you build them.
The GUI Builder's various windows include:
Design Area. The GUI Builder's primary window for creating and editing Java GUI forms. The toolbar's
Source button enables you to view a class's source code, the Design button allows you to view a graphical view
of the GUI components, the History button allows you to access the local history of changes of the file. The
additional toolbar buttons provide convenient access to common commands, such as choosing between
Selection and Connection modes, aligning components, setting component auto-resizing behavior, and
previewing forms.
Navigator. Provides a representation of all the components, both visual and non-visual, in your
application as a tree hierarchy. The Navigator also provides visual feedback about what component in the tree is
currently being edited in the GUI Builder as well as allows you to organize components in the available panels.
Palette. A customizable list of available components containing tabs for JFC/Swing, AWT, and
JavaBeans components, as well as layout managers. In addition, you can create, remove, and rearrange the
categories displayed in the Palette using the customizer.
Properties Window. Displays the properties of the component currently selected in the GUI Builder,
Navigator window, Projects window, or Files window.
If you click the Source button, the IDE displays the application's Java source code in the Editor with sections of
code that are automatically generated by the GUI Builder indicated by grey areas (they become blue when
selected), called Guarded Blocks. Guarded blocks are protected areas that are not editable in Source view. You
can only edit code appearing in the white areas of the Editor when in Source view. If you need to make changes
to the code within a Guarded Block, clicking the Design button returns the IDE's Editor to the GUI Builder where
you can make the necessary adjustments to the form. When you save your changes, the IDE updates the file's
sources.
Note: For advanced developers, the Palette Manager is available that enables you to add custom components
from JARs, libraries, or other projects to the Palette. To add custom components through the Palette Manager,
choose Tools > Palette > Swing/AWT Components.
Key Concepts
The IDE's GUI Builder solves the core problem of Java GUI creation by streamlining the workflow of creating
graphical interfaces, freeing developers from the complexities of Swing layout managers. It does this by
extending the current NetBeans IDE GUI Builder to support a straightforward "Free Design" paradigm with simple
layout rules that are easy to understand and use. As you lay out your form, the GUI Builder provides visual
guidelines suggesting optimal spacing and alignment of components. In the background, the GUI Builder
translates your design decisions into a functional UI that is implemented using the new GroupLayout layout
manager and other Swing constructs. Because it uses a dynamic layout model, GUI's built with the GUI Builder
behave as you would expect at runtime, adjusting to accommodate any changes you make without altering the
To add a JPanel:
1. In the Palette window, select the Panel component from the Swing
Containers category by clicking and releasing the mouse button.
2. Move the cursor to the upper left corner of the form in the GUI Builder.
When the component is located near the container's top and left
edges, horizontal and vertical alignment guidelines appear indicating
the preferred margins. Click in the form to place the JPanel in this
location.
The JPanel component appears in the ContactEditorUI form
with orange highlighting signifying that it is selected. After releasing
the mouse button, small indicators appear to show the component's
anchoring relationships and a corresponding JPanel node is displayed
in the Navigator window, as shown in the following illustration.
Next, we need to resize the JPanel to make room for the components we'll place within it a little later, but let's
take a minute to point out another of the GUI Builder's visualization features first. In order to do this we need to
deselect the JPanel we just added. Because we haven't added a title border yet, the panel disappears. Notice,
however, that when you pass the cursor over the JPanel, its edges change to light gray so that its position can be
clearly seen. You need only to click anywhere within the component to reselect it and cause the resize handles
and anchoring indicators to reappear.
Now that we've added a panel to contain our UI's Name information, we need to repeat the process to add
another directly below the first for the E-mail information. Referring to the following illustrations, repeat the
previous two tasks, paying attention to the GUI Builder's suggested positioning. Notice that the suggested vertical
spacing between the two JPanels is much narrower than that at the edges. Once you have added the second
JPanel, resize it such that it fills the form's remaining vertical space.
Because we want to visually distinguish the functions in the upper and lower sections of our GUI, we need to add
a border and title to each JPanel. First we'll accomplish this using the Properties window and then we'll try it
using the pop-up menu.
Before proceeding further, we need to add an additional JLabel and JTextField immediately to the right of those
we just added, as shown in the following illustration. This time enter Last Name: as the JLabel's display text
and leave the JTextFields' placeholder text as it is for now.
To resize a JTextField:
1. Select the JTextField we just added to the right of the Last
Name: JLabel.
2. Drag the JTextField's right edge resize handle toward the right edge
of the enclosing JPanel.
3. When the vertical alignment guidelines appear suggesting the margin
between the text field and right edge of the JPanel, release the mouse
button to resize the JTextField.
The JTextField's right edge snaps into alignment with the JPanel's
recommended edge margin, as shown in the following illustration.
Before moving on, we need to edit the JLabels' name so that we'll be able to see the effect of the alignments we'll
set later.
Inserting Components
Engr. Farhan Ahmed Umrani Page 153
Object Oriented Programming
Note: Refer to the Inserting components (.swf) screencast for an interactive demo on the section below.
Often it is necessary to add a component between components that are already placed in a form. Whenever you
add a component between two existing components, the GUI Builder automatically shifts them to make room for
the new component. To demonstrate this, we'll insert a JTextField between the JLabels we added previously, as
shown in the following two illustrations.
We still need to add one additional JTextField to the form that will display each contact's nickname on the right
side of the form.
To add a JTextField:
1. In the Palette window, select the Text Field component from the
Swing category.
2. Move the cursor to the right of the Nickname label and click to place
the text field.
The JTextField snaps into position next to the JLabel on its left.
To resize a JTextField:
1. Drag the resize handles of the Nickname: label's JTextField you
added in the previous task toward the right of the enclosing JPanel.
2. When the vertical alignment guidelines appear suggesting the margin
between the text field and JPanel edges, release the mouse button to
resize the JTextField.
The JTextField's right edge snaps into alignment with the JPanel's
recommended edge margin and the GUI Builder infers the appropriate
resizing behavior.
3. Press Ctrl-S to save the file.
Moving Forward
Alignment is one of the most fundamental aspects of creating professional-looking GUIs. In the previous section
we got a glimpse of the IDE's alignment features while adding the JLabel and JTextField components to our
ContactEditorUI form. Next, we'll take a more in depth look at the GUI Builder's alignment features as we work
with the various other components we need for our application.
Component Alignment
Note: Refer to the Aligning and anchoring components (.swf) screencast for an interactive demo on the sections
below.
Every time you add a component to a form, the GUI Builder effectively aligns them, as evidenced by the
alignment guidelines that appear. It is sometimes necessary, however, to specify different relationships between
groups of components as well. Earlier we added four JLabels that we need for our ContactEditor GUI, but we
didn't align them. Now we'll align the two columns of JLabels so that their right edges line up.
To align components:
1. Hold down the Ctrl key and click to select the First
Name: and Title: JLabels on the left side of the form.
2. Click the Align Right in Column button ( ) in the toolbar. Alternately,
you can right-click either one and choose Align > Right in Column
from the pop-up menu.
3. Repeat this for the Last Name: and Nickname: JLabels as well.
The JLabels' positions shift such that the right edges of their display
text are aligned. The anchoring relationships are updated, indicating
that the components have been grouped.
Before we're finished with the JTextFields we added earlier, we need to make sure that the two JTextFields we
inserted between the JLabels are set to resize correctly. Unlike the two JTextFields that we stretched to the right
edge of our form, inserted components' resizeability behavior isn't automatically set.
1. In the Palette window, select the Label component from the Swing
category.
2. Move the cursor below the First Name and Title JLabels on the
left side of the JPanel. When the guideline appears indicating that the
new JLabel's right edge is aligned with the right edges of the
component group above (the two JLabels), click to position the
component.
The JLabel snaps into a right-aligned position with the column of
JLabels above, as shown in the following illustration. The GUI Builder
updates the alignment status lines indicating the component's spacing
and anchoring relationships.
As in the previous examples, double-click the JLabel to select its display text and then enter Display
Format: for the display name. Notice that when the JLabel snaps into position, the other components shift to
accommodate the longer display text.
Baseline Alignment
Whenever you add or move components that include text (JLabels, JTextFields, and so forth), the IDE suggests
alignments which are based on the baselines of the text in the components. When we inserted the JTextField
earlier, for example, its baseline was automatically aligned to the adjacent JLabels.
Now we'll add the combo box that will enable users to select the format of the information that our ContactEditor
application will display. As we add the JComboBox, we'll align its baseline to that of the JLabel's text. Notice once
again the baseline alignment guidelines that appear to assist us with the positioning.
2. Drag the resize handle on the JComboBox's right edge toward the
right until the alignment guidelines appear suggesting the preferred
offset between the JComboBox and JPanel edges.
As shown in the following illustration, the JComboBox's right edge
snaps into alignment with the JPanel's recommended edge margin
and the component's width is automatically set to resize with the form.
Navigator window.
To add a JTextField:
1. In the Palette window, select the Text Field component from the
Swing Controls category.
2. Move the cursor immediately to the right of the E-mail
Address label we just added. When the guidelines appear indicating
that the JTextField's baseline is aligned with the baseline of the text in
the JLabel and the margin between the two components is suggested
with a vertical guideline, click to position the text field.
The JTextField snaps into position on the right of the E-mail
Address: JLabel and is chained to the JLabel. Its corresponding
node is also added to the Inspector window.
3. Drag the resize handle of the JTextField toward the right of the
enclosing JPanel until the alignment guidelines appear suggesting the
offset between the JTextField and JPanel edges.
The JTextField's right edge snaps to the alignment guideline
indicating the preferred margins.
Now we need to add the JList that will display our ContactEditor's entire contact list.
Since JLists are used to display long lists of data, they typically require the addition of a JScrollPane. Whenever
you add a component which requires a JScrollPane, the GUI Builder automatically adds it for you. Because
JScrollPanes are non-visual components, you have to use the Inspector window in order to view or edit any
JScrollPanes that the GUI Builder created.
Component Sizing
Note: Refer to the Resizing and indenting components (.swf) screencast for an interactive demo on the sections
below.
It is often beneficial to set several related components, such as buttons in modal dialogues, to be the same size
for visual consistency. To demonstrate this we'll add four JButtons to our ContactEditor form that will allow us to
add, edit, and remove individual entries from our contact list, as shown in the following illustrations. Afterwards,
we'll set the four buttons to be the same size so they can be easily recognized as offering related functionality.
3. Move the cursor over the top right corner of the JList in the lower
JPanel. When the guidelines appear indicating that the JButton's top
and right edges are aligned with that of the JList, shift-click to place
the second button along the JFrame's right edge.
4. Add two additional JButtons below the two we already added to create
a column. Make certain to position the JButtons such that the
suggested spacing is respected and consistent. If you forget to
release the Shift key prior to positioning the last JButton, simply press
the Escape key.
5. Set the display text for each JButton. (You can edit a button's text by
right-clicking the button and choosing Edit Text. Or you can click the
button, pause, and then click again.) Enter Add for the top
button, Edit for the second, Remove for the third, and As
Default for the fourth.
The JButton components snap into the positions designated by the
alignment guidelines. The width of the buttons changes to
accommodate the new names.
Now that the buttons are positioned where we want them, we'll set the four buttons to be the same size for visual
consistency as well as to clarify that they are related functionally.
Indentation
Often it is necessary to cluster multiple components under another component such that it is clear they belong to
a group of related functions. One typical case, for example, is placing several related checkboxes below a
common label. The GUI Builder enables you to accomplish indenting easily by providing special guidelines
suggesting the preferred offset for your operating system's look and feel.
In this section we'll add a few JRadioButtons below a JLabel that will allow users to customize the way the
application displays data. Refer to the following illustrations while accomplishing this or click the View Demo link
following the procedure to view an interactive demonstration.
Now we need to add the three JRadioButtons to a ButtonGroup to enable the expected toggle behavior in which
only one radio button can be selected at a time. This will, in turn, ensure that our ContactEditor application's
contact information will be displayed in the mail format of our choosing.
Finishing Up
Now we need to add the buttons that will enable users to confirm the information they enter for an individual
contact and add it to the contact list or cancel, leaving the database unchanged. In this step, we'll add the two
required buttons and then edit them so that they appear the same size in our form even though their display text
are different lengths.
4. Add another JButton to the left of the first, making certain to place it
using the suggested spacing along the JFrame's bottom edge.
5. Set the display text for each JButton. Enter OK for the left button
and Cancel for right one. Notice that the width of the buttons
changes to accommodate the new names.
6. Set the two JButtons to be the same size by selecting both, right-
clicking either, and choosing Same Size > Same Width from the pop-
up menu.
Introduction
Creating the Application Form
Adding a Package for the Image
Displaying the Image on the Label
Building and Running the Application
Creating Custom Code
Summary
See Also
To complete this tutorial, you need the following software and resources.
Software or Resource Version Required
Introduction
5. Click Finish.
2. Right-click the Source Packages node and choose New > JFrame Form.
3. For Class Name, type ImageDisplay.
5. Click Finish.
To add the JLabel:
In the Palette, select the Label component and drag it to the JFrame.
For now, the form should look something like the following image:
2. Click Finish.
In the Projects window, you should see a new package appear within the Source Packages folder.
Displays your image on the label in the Design view of your form.
At this point, you can do some simple things to improve the appearance of the form, such as:
In the Properties window, select the text property and delete jLabel1. That value was generated by
the GUI Builder as display text for the label. However, you are using the label to display an image rather than
text, so that text is not needed.
The getResource method is also useful for accessing other types of resources, such as text files that
contain data that your application might need to use.
To register event handlers for mouse events on the Jlabel:
In the Design View, right-click the JLabel and choose Events > Mouse >
mouseClicked/mousePressed/mouseReleased from the popup menu.
An event handler is generated for the corresponding event.
Note: You can get the mouse coordinates (for example, the location of a mouse click) in the event handler using
the event.getPoint(), event.getX(), or event.getY() methods. See Class MouseEvent for
details.
3. From the dropdown list at the top of the dialog box, select the Custom Code option.
The Custom Code option in this property editor lets you fill in the parameter of the setIcon method yourself.
You can fill in this parameter with the necessary logic or with a call to a separate method that you have hand-
coded elsewhere in the class.
Summary
This tutorial has shown you how to access images from an application that you create in the NetBeans IDE.
Note: uses JLabel's setIcon method to apply the icon to the label. In the Java Tutorial example, the icon is
applied to the label by being passed through its constructor.