Nothing Special   »   [go: up one dir, main page]

OOP Complete

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 173

Object Oriented Programming

LAB # 01
GETTING FAMILIAR WITH JAVA in NetBeans
Objective:
To get a hands on training exposure to the Java development environment in net beans.

How to Install NetBeans 8.1:


Step 0: Install JDK
To use NetBeans for Java programming, you need to first install Java Development Kit
(JDK). See "JDK - How to Install".
Step 1: Download
Download "NetBeans IDE" installer from http://netbeans.org/downloads/index.html. There
are many "bundles" available. For beginners, choose the "Java SE" (e.g., " netbeans-8.1-javase-
windows.exe").
Step 2: Run the Installer
Run the downloaded installer.

Writing a Hello-world Java Program in NetBeans:


Step 0: Launch NetBeans
Launch NetBeans. If the "Start Page" appears, close it by clicking the "close" button.
Step 1: Create a New Project
For each Java application, you need to create a "project" to keep all the source files, classes
and relevant resources.
1. From "File" menu ⇒ Choose "New Project...".
2. In "Choose Project" diglog ⇒ Under "Categories", choose "Java" ⇒ Under "Projects",
choose "Java Application" ⇒ "Next".
3. In "Name and Location" ⇒ Under "", enter "MyConsole1" ⇒ In "Project Location",
select a suitable directory to save your works ⇒ "Create Main class" ⇒ Finish.

Engr. Farhan Ahmed Umrani Page 1


Object Oriented Programming

Type the name MyConsole1.

Engr. Farhan Ahmed Umrani Page 2


Object Oriented Programming

Project is created.

2) EDIT CODES
Replace the line “// TODO …” with the following codes.

1. /** First Java Program to MyConsole1*/


2. public class MyConsole1 {
3. public static void main(String[] args) {
4. System.out.println("Hello, world");
5. }

}
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.

Engr. Farhan Ahmed Umrani Page 3


Object Oriented Programming

 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}

Let us use the graphic debugger to debug the program.


Step 1: Set an initial Breakpoint
A breakpoint suspends program execution for you to examine the internal states of the
program. Before starting the debugger, you need to set at least one breakpoint to suspend the
execution inside the program. Set a breakpoint at main() method by clicking on the left-
margin of the line containing main(). A red circle or an inverted Triangle appears in the left-
margin indicating a breakpoint is set at that line.

Engr. Farhan Ahmed Umrani Page 4


Object Oriented Programming

Step 2: Start Debugging


Right click anywhere on the source code ⇒ "Debug File". The program begins execution but
suspends its operation at the breakpoint, i.e., the main()method.
As illustrated in the following diagram, the highlighted line (also pointed to by a green arrow)
indicates the statement to be executed in the next step.

Step 3: Step-Over and Watch the Variables and Outputs


Click the "Step Over" button (or select "Step Over" in "Debug" menu) to single-step thru
your program. At each of the step, examine the value of the variables (in the "Variable"
panel) and the outputs produced by your program (in the "Output" Panel), if any. You can
also place your cursor at any variable to inspect the content of the variable.

Engr. Farhan Ahmed Umrani Page 5


Object Oriented Programming

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!

Step 4: Breakpoint, Run-To-Cursor, Continue and Finish


As mentioned, a breakpoint suspends program execution and let you examine the internal
states of the program. To set a breakpoint on a particular statement, click on the left-margin
of that line (or select "Toggle Breakpoint" from "Run" menu).
"Continue" resumes the program execution, up to the next breakpoint, or till the end of the
program.
"Single-step" thru a loop with a large count is time-consuming. You could set a breakpoint at
the statement immediately outside the loop (e.g., Line 11 of the above program), and issue
"Continue" to complete the loop.
Alternatively, you can place the cursor on a particular statement, and issue "Run-To-Cursor"
to resume execution up to the line.
"Finish" ends the debugging session. Always terminate your current debugging session using
"Finish" or "Continue" till the end of the program.

3.1   Other Debugger's Features:


Modify the Value of a Variable

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.

Engr. Farhan Ahmed Umrani Page 6


Object Oriented Programming

4.     NetBeans - Tips & Tricks


4.1   General Usage

These are the features that I find to be most useful in NetBeans:


1. Maximizing Window (double-click):  You can double-click on the
"header" of any panel to maximize that particular panel, and double-click again
to restore it back. This is particularly useful for editing source code in full panel.
2. Code Auto-Complete (or Intelli-Sense) (ctrl-space):  Enter a
partial statement (e.g., Sys) and press control-space to activate the auto-complete,
which displays all the available choices.
3. Javadoc (ctrl-space, alt-F1): Place the cursor on a method or class, and
press ctrl-space to view the javadoc; or right-click ⇒ Show Javadoc (alt-F1) to open it
on a browser.
4. Code Shorthand (tab):  For example, you can enter "sout" and press TAB for
"System.out.println"; "psvm" for "public static void main(String[] args) { }" or "fori" +
tab for a for-loop. To view and configure code template, choose "Tools" menu ⇒
"Options" ⇒ "Editor" ⇒ "Code Templates".
5. Formatting Source Code (alt-shift-f):  Right-click on the source (or
from the "Source" menu) ⇒ Choose "Format". NetBeans will layout your source codes
with the proper indents and format. To configure the formatting, choose "Tools" menu
⇒ "Options" ⇒ "Editor" ⇒ "Formatting".
You can also select the section of codes to be formatted, instead of the entire file.
6. Hints for Correcting Syntax Error:  If there is a syntax error on a
statement, a red mark will show up on the left-margin on that statement. You could
click on the "light bulb" to display the error message, and also select from the available
hints for correcting that syntax error.
7. Rename (Refactor) (ctrl-r):  To rename a variable, place the cursor on that
variable, right-click ⇒ "Refactor" ⇒ "Rename" ⇒ Enter the new name. All the
appearances of that variables in the project will be renamed.
8. Small Programs:  You can keep many small toy programs (with main()) in one
Java project instead of create a new project for each small program. To run the desired
program, on the "editor" panel ⇒ right-click ⇒ "Run File".
9. Source Toggle Comment:  To temporarily comment-off a block of codes,
choose "Source" ⇒ "Toggle Comment".
10. Error Message Hyperlink:  Click on an error message will hyperlink to the
corresponding source statement.
11. Command-Line Arguments:  To provide command-line arguments to your
Java program in NetBeans, right-click on the "project" ⇒ "Set as Main Project" ⇒ "Set
Configurations" ⇒ "Customize..." ⇒ "Run" ⇒ select the "Main" class ⇒ type your

Engr. Farhan Ahmed Umrani Page 7


Object Oriented Programming

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:

1. Get familiarize with the netbean Environment.


2. Practice the above program.
3. Write a program which gives output by showing ; your roll number &
your name .
Note:
 Get the snapshot of the output of program by clicking key print screen
and there after save in some word file.
 The working of yours would be checked by that snapshot of work.

Engr. Farhan Ahmed Umrani Page 8


Object Oriented Programming

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.

There are two data types available in Java:

1. Primitive Data Types


2. Reference/Object class

Data Types Primitive:


There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and named by a key word. Let us now
look into detail about the eight primitive data types.
 byte: Byte data type is a 8-bit signed two's complement integer.

 Minimum value is -128 (-2^7)


 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an int.
 Example : byte a = 100 , byte b = -50

 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

Engr. Farhan Ahmed Umrani Page 9


Object Oriented Programming

 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 >

Engr. Farhan Ahmed Umrani Page 10


Object Oriented Programming

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'

Reference Data Types:


 Reference variables are created using defined constructors of the classes.
They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. For example, Employee, Puppy etc.
 Class objects, and various type of array variables come under reference data
type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type
or any compatible type.
 Example : Animal animal = new Animal("giraffe");

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:

Engr. Farhan Ahmed Umrani Page 11


Object Oriented Programming

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)

Command line arguments :

Engr. Farhan Ahmed Umrani Page 12


Object Oriented Programming

 Command Line Arguments can be used to specify configuration information while


launching your application.
 There is no restriction on the number of command line arguments.You can specify
any number of arguments
 Information is passed as Strings.
 They are captured into the String argument of your main method

NetBeans 8 Basic Console Input Output [CIO]

STEPS

1) START NETBEANS.

2) CREATE A NEW PROJECT.

2-1) Select Java Application.

2-2) Type the name MyConsole1.

2-3) Project is created.

3) EDIT CODES
3-1) Replace the line “// TODO …” with the following codes.

    Scanner sc = new Scanner(System.in);

    System.out.print("Please enter your weight: ");

    int weight = sc.nextInt();

    System.out.println("Weight = " + weight);

Press SHIFT-ALT-F to realign your codes.

3-2) Notice some syntax errors.

3-3) If you hover your mouse over the red underlined text, you will get some help
message.

Engr. Farhan Ahmed Umrani Page 13


Object Oriented Programming

3-4) Choose “Add import for java.util.Scanner”

3-5) NetBeans add the import line.

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.

Engr. Farhan Ahmed Umrani Page 14


Object Oriented Programming

3-7) Run again but this time enter “sixty” instead of a number 60.

3-8) You will get an error message.

3-9) Replace the codes in Step 3-1.


    Scanner sc = new Scanner(System.in);
    System.out.print("Please enter your weight: ");
    int weight;
    // Accept input and test to see if it’s an integer
    if (sc.hasNextInt()) {
       // Success, it was an integer so get it
       weight = sc.nextInt();
       System.out.println("Weight = " + weight);
    } else {
        // Failure so retrieve the input as a String
        String bad = sc.next();
        // Inform the user what went wrong
        System.out.println(bad + " cannot be converted to an integer");
  }

Engr. Farhan Ahmed Umrani Page 15


Object Oriented Programming

3-10) Run.

3-11) Enter “sixty”.

3-12) Finally, replace the current codes with the following


    Scanner sc = new Scanner(System.in);
    System.out.println("Select an Account");
    System.out.println("A: Savings");
    System.out.println("B: Checking");
    System.out.println("C: Exit");
    System.out.print("Please choose A, B or C: ");
    char letter;
    if (sc.hasNext("[A-Ca-c]")) {
        String choice = sc.next();
        letter = choice.toUpperCase().charAt(0);
        System.out.println("You chose: " + letter);
    } else {
        String choice = sc.next();
        System.out.println(choice + " is not valid input");
  }

Engr. Farhan Ahmed Umrani Page 16


Object Oriented Programming

3-13) Outcome:

Assignment:

 Write any program in which you use command line argument.


 Write any program in which you use all above commands.
 Write any program using scanner library.

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:

Engr. Farhan Ahmed Umrani Page 17


Object Oriented Programming

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:

Engr. Farhan Ahmed Umrani Page 18


Object Oriented Programming

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");
}}

The switch Statement


You use the switch statement to select from multiple choices based on a set of fixed values
for a given expression. The expression must produce a result of an integer type other than
long, or a value of an enumeration type. Thus, the expression that controls a switch statement
can result in a value of type
char, byte, short, or int, or an enumeration constant.
In normal use the switch statement operates rather like a rotary switch in that you can select
one of a fixed number of choices. For example, on some makes of washing machine you
choose between the various possible machine settings in this way, with positions for cotton,
wool, synthetic fiber, and so on,
which you select by turning the knob to point to the option that you want.
Here’s a switch statement reflecting this logic for a washing machine:

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;
}

LOOP( for, while, do-while, )


The for loop
The for loop is used to repeat a task a set number of times. It has three parts.

Engr. Farhan Ahmed Umrani Page 20


Object Oriented Programming

 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.

The while loop


The while loop works differently than the for loop. The for loop repeats a
segment of code a specific number of times, while the while loop repeats a segment of code
an unknown number of times. The code within a while loop will execute while the specified
condition is true.
Syntax:
while(condition is true)
{
//block of code
}
Example:
Int num = 0;
Engr. Farhan Ahmed Umrani Page 21
Object Oriented Programming

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.

The do-while loop


The do-while loop is very similar to the while loop, but it does things in reverse order. The
while loop - while a condition is true, perform a certain action, the do-while loop - perform a
certain action while a condition is true. Also, the code within a do-while loop will always
execute at least once, even if the specified condition is false. This is because the code is
executed before the condition is tested.

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

Engr. Farhan Ahmed Umrani Page 22


Object Oriented Programming

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:

Engr. Farhan Ahmed Umrani Page 23


Object Oriented Programming

❑ 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:

❑ Non-static fields, also called instance variables


Each object of the class will have its own copy of each of the non-static fields or instance
variables that appear in the class definition. Each object will have its own values for each
instance variable. The name instance variable originates from the fact that an object is an
instance or an occurrence of a class, and the values stored in the instance variables for the
object differentiate the object from others of the same class type. An instance variable is
declared within the class definition in the usual way, with a type name and a variable name,
and can have an initial value specified.

❑ Static fields, also called class variables


A given class will have only one copy of each of its static fields or class variables, and these
will be shared between and among all the objects of the class. Each class variable exists even
if no objects of the class have been created. Class variables belong to the class, and they can
be referenced by any object or class method, not just methods belonging to instances of that
class. If the value of a static field is changed, the new value is available equally in all the
objects of the class. This is quite different from non-static fields, where changing a value for
one object does not affect the values in other objects. A static field must be declared using the
keyword static preceding the type name.

Engr. Farhan Ahmed Umrani Page 24


Object Oriented Programming

Methods in a Class Definition


The methods that you define for a class provide the actions that can be carried out using the
variables specified in the class definition. Analogous to the variables in a class definition are
two varieties of methods— instance methods and class methods. You can execute class
methods even when no objects of a class exist, whereas instance methods can be executed
only in relation to a particular object, so if no objects exist, you have no way to execute any
of the instance methods defined in the class. Again, like class variables, class methods are
declared using the keyword static, so they are sometimes referred to as static methods.

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.

Creating Objects of a Class


When you declare a variable of type Sphere with the following statement:
Sphere ball; // Declare a variable
To create an object of a class you must use the keyword new followed by a call. To initialize
ball with a reference to an object, you could write:

ball = new Sphere( ); // Create a sphere

you can do the whole thing in one step, with the following statement:

Engr. Farhan Ahmed Umrani Page 25


Object Oriented Programming

Sphere ball = new Sphere( ); // Create a sphere

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.

Accessing Variables and Methods


You can access a static member of a class using the class name, followed by a period,
followed by the member name. With a class method you also need to supply the parentheses
enclosing any arguments to the method after the method name. The period here is called the
dot operator. So, if you wanted to calculate the square root of (, you could access the class
method sqrt() and the class variable PI that are defined in the Math class as follows:

double rootPi = Math.sqrt(Math.PI);

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

double xCenter; // 3D coordinates


double yCenter; // of the center

Engr. Farhan Ahmed Umrani Page 26


Object Oriented Programming

double zCenter; // of a sphere

// Plus the rest of the class definition...


}

*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.

Returning from a Method


To return a value from a method when its execution is complete you use a return statement.

return return_value; // Return a value from a method.

If a method does not return a value, you can just use the keyword return by itself to end
execution of the method:

return; // Return from a method

Engr. Farhan Ahmed Umrani Page 27


Object Oriented Programming

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.

The Parameter List


The parameter list appears between the parentheses following the method name.

❑ 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.

How Argument Values Are Passed to a Method

Engr. Farhan Ahmed Umrani Page 28


Object Oriented Programming

You can specify any of the parameters for a method as final.

Defining Class Methods


You define a class method by adding the keyword static to its definition. For example, the
class Sphere could have a class method to return the value stored in the static variable count:

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

Engr. Farhan Ahmed Umrani Page 29


Object Oriented Programming

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...
}

The Variable “this”


Every instance method has a variable with the name this that refers to the current object for
which the method is being called. The compiler uses this implicitly when your method refers
to an instance variable of the class. For example, when the method volume() refers to the
instance variable radius, the compiler will insert the this object reference so that the reference
will be equivalent to this.radius. The return statement in the definition of the volume()
method is actually:

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:

void changeRadius(double radius)


{
// Change the instance variable to the argument value
this.radius = radius;
}

In the body of the changeRadius() method, this.radius refers to the instance variable, and
radius

Engr. Farhan Ahmed Umrani Page 30


Object Oriented Programming

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.

 Define a class, “rectanglebus” it calculates the capacity of bus according to input


values(length & width) or (no. of seat) of bus and return the available free space of
bus. Make static and non-static methods to calculate the capacity of bus by two ways
e.g. by length & width and by no. of seat.

Engr. Farhan Ahmed Umrani Page 31


Object Oriented Programming

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

Engr. Farhan Ahmed Umrani Page 32


Object Oriented Programming

}
// 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.

The Default Constructor


As I said, if you don’t define any constructors for a class, the compiler will supply a default
constructor that has no parameters and does nothing.

Sphere()
{
}

Creating Objects of a Class


When you declare a variable of type Sphere with the following statement:
Sphere ball; // Declare a variable
no constructor is called because no object is created. All you have created at this point is the
variable ball, which can store a reference to an object of type Sphere, if and when you create
one.

Engr. Farhan Ahmed Umrani Page 33


Object Oriented Programming

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:

ball = new Sphere(10.0, 1.0, 1.0, 1.0); // Create a sphere

you can do the whole thing in one step, with the following statement:

Sphere ball = new Sphere(10.0, 1.0, 1.0, 1.0); // Create a sphere

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.

Passing Objects to a Method


When you pass an object as an argument to a method, the mechanism that applies is called
pass-by reference, because a copy of the reference contained in the variable is transferred to
the method, not a copy of the object itself.

The Lifetime of an Object


The lifetime of an object is determined by the variable that holds the reference to it—
assuming there is only one. If you have the declaration
Sphere ball = new Sphere(10.0, 1.0, 1.0, 1.0); // Create a sphere
Engr. Farhan Ahmed Umrani Page 34
Object Oriented Programming

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;

Defining and Using a Class


To put what you know about classes to use, you can use the Sphere class in an example.

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.

Using the Sphere Class


class CreateSpheres
{
public static void main(String[] args) {
System.out.println("Number of objects = " + Sphere.getCount());
Engr. Farhan Ahmed Umrani Page 35
Object Oriented Programming

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());
// Output the volume of each sphere
System.out.println("ball volume = " + ball.volume());
System.out.println("globe volume = " + globe.volume());
}
}

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.

Multiple Constructors for the Sphere Class


The code for the extra constructors is as follows:

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;

Engr. Farhan Ahmed Umrani Page 36


Object Oriented Programming

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

Engr. Farhan Ahmed Umrani Page 37


Object Oriented Programming

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

*) The Point Class


You first define a basic class for point objects:

import static java.lang.Math.sqrt;

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

Engr. Farhan Ahmed Umrani Page 38


Object Oriented Programming

}
// 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”
}
}

*) The Line Class


You can use Point objects in the definition of the class Line:

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)”
}

*) Note how the constructor that accepts Point objects works:

Engr. Farhan Ahmed Umrani Page 39


Object Oriented Programming

// 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 points - a poor implementation!


Line(final Point start, final Point end) {
this.start = start; // Dependent on external object!!!
this.end = end; // Dependent on external object!!!
}

*) The TryGeometry Class


public class TryGeometry
{
public static void main(String[] args)
{
// Create two points and display them
Point start = new Point(0.0, 1.0);
Point end = new Point(5.0, 6.0);
System.out.println(“Points created are “ + start + “ and “ + end);
// Create two lines and display them
Line line1 = new Line(start, end);
Line line2 = new Line(0.0, 3.0, 3.0, 0.0);
System.out.println(“Lines created are “ + line1 + “ and “ + line2);
// Display the intersection
System.out.println(“Intersection is “ + line2.intersects(line1));
// Now move the end point of line1 and show the new intersection
end.move(1.0, -5.0);
System.out.println(“Intersection is “ + line1.intersects(line2));
}
}

*) 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));
System.out.println(“7.5 to the power 0 is “ + power(7.5,0));
System.out.println(“10 to the power -2 is “ + power(10,-2));
}
// Raise x to the power n

Engr. Farhan Ahmed Umrani Page 40


Object Oriented Programming

static double power(double x, int n) {


if(n > 1)
return x*power(x, n-1); // Recursive call
else if(n < 0)
return 1.0/power(x, -n); // Negative power of x
else
return n == 0 ? 1.0 : x; // When n is 0 return 1, otherwise x
}
}

Assignment:
 Practice the above programs.

 Define a class, mcmLength, to represent a length measured in meters, centimeters,


and millimeters, each stored as integers. Include methods to add and subtract objects,
to multiply and divide an object by an integer value, to calculate an area resulting
from the product of two objects, and to compare objects. Include constructors that
accept three arguments—meters, centimeters, and millimeters; one integer argument
in millimeters; one double argument in centimeters; and no arguments, which creates
an object with the length set to zero. Check the class by creating some objects and
testing the class operations.

LAB # 06

Engr. Farhan Ahmed Umrani Page 41


Object Oriented Programming

Final Keyword & Packages


Objective:
 Use of final keyword in java
 Understanding packages and adding class from a package to the program.
 Controlling Access to Class Members by using Access Attributes

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

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.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable


Engr. Farhan Ahmed Umrani Page 42
Object Oriented Programming

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

2) Java final method


If you make any method as final, you cannot override it.

Example of final method

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

3) Java final class


Engr. Farhan Ahmed Umrani Page 43
Object Oriented Programming

If you make any class as final, you cannot extend it.

Example of final class

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

Q) Is final method inherited?

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...

Q) What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final
variable.

Engr. Farhan Ahmed Umrani Page 44


Object Oriented Programming

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.

It can be initialized only in constructor.

Example of blank final variable

1. class Student{  
2. int id;  
3. String name;  
4. final String PAN_CARD_NUMBER;  
5. ...  
6. }  

Q) Can we initialize blank final variable?

Yes, but only in constructor. For example:

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

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.

Engr. Farhan Ahmed Umrani Page 45


Object Oriented Programming

Example of static blank final variable

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. }  

Q) What is final parameter?

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

Q) Can we declare a constructor final?

No, because constructor is never inherited.

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

Engr. Farhan Ahmed Umrani Page 46


Object Oriented Programming

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.

Adding Classes from a Package to Your Program


You used the import statement frequently in examples but nonetheless I’ll describe it here
from the ground up. Assuming they have been defined with the public keyword, you can add
all or any of the classes in a named package to the code in your program by using an import
statement. You can then reference the classes that you make available to your program
through the import statement just by using the class names. For example, to make available
all the classes in the package Geometry.Shapes3D to a source file, you just need to add the
following import statement to the beginning of the file:

import Geometry.Shapes3D.*; // Include all classes from this 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:

import Geometry.Shapes3D.Sphere; // Include the class Sphere

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.

Packages and Names in Your Programs


If you don’t use an import statement to incorporate the class in your program, you can still
make use of the class by referring to it using its full class name. If you needed to do this with
the class Sphere, you might declare a variable with the statement:

Geometry.Shapes3D.Sphere ball = new Geometry.Shapes3D.Sphere(10.0, 1.0, 1.0, 1.0);


Importing Static Class Members
As you have seen in some of the examples, you can import the names of static members of a
class from a named package into your program. This allows you to reference such static
members by their simple unqualified names.
double volume()
{
return 4.0/3.0*Math.PI*radius*radius*radius;

Engr. Farhan Ahmed Umrani Page 47


Object Oriented Programming

You can remove the need for prefixing PI with the Math class name by importing the PI
member name from the Math class:

import static java.lang.Math.PI;


class Sphere
{
// Class details as before...
double volume()
{
return 4.0/3.0*PI*radius*radius*radius;
}
}
Standard Packages
All of the standard classes that are provided with Java are stored in standard packages. There
is a substantial and growing list of standard packages (more than 150 in JDK 5) but some of
the ones you may hear about most frequently are:

Engr. Farhan Ahmed Umrani Page 48


Object Oriented Programming

Controlling Access to Class Members:

Using Access Attributes


Let’s start by considering classes that are in the same package. Within a given package, any
class has direct access to any other class name in the same package—for declaring variables
or specifying method parameter types, for example—but the variables and methods that are
members of that other class are not necessarily accessible. The accessibility of these is
controlled by access attributes. The name of a class in one package can be accessed from a
class in another package only if the class to be accessed is declared as public. Classes not
declared as public can be accessed only by classes within the same package.

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.

Engr. Farhan Ahmed Umrani Page 49


Object Oriented Programming

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.

Engr. Farhan Ahmed Umrani Page 50


Object Oriented Programming

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:

public class Outside {


// Nested class
public class Inside {
// Details of Inside class...
}
// More members of Outside class...
}
Here the class Inside is nested inside the class Outside. The Inside class is declared as a
public member of Outside, so it is accessible from outside Outside. Obviously, a nested class
should have some specific association with the enclosing class. Arbitrarily nesting one class
inside another would not be sensible. The enclosing class here is referred to as a top-level
class. A top-level class is a class that contains a nested class but is not itself a nested class.
Outside outer = new Outside();

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:

Engr. Farhan Ahmed Umrani Page 51


Object Oriented Programming

Outside.Inside inner = outer.new Inside(); // Define a nested class object

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:

Inside inner = new Inside(); // Define a nested class object

This statement is equivalent to:


this.Inside inner = this.new Inside(); // Define a nested class object

Static Nested Classes:


To make objects of a nested class type independent of objects of the enclosing class type, you
can declare the nested class as static:

public class Outside {


public static class Skinside{
// Details of Skinside
}
// Nested class
public class Inside {
// Details of Inside class...
}
// More members of Outside class...
}

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:

Outside.Skinside example = new Outside.Skinside();

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.

Rabbits out of Hats


Let’s add the detail of the MagicHat class definition:

import java.util.Random; // Import Random class


public class MagicHat {
static int maxRabbits = 5; // Maximum rabbits in a hat
static Random select = new Random(); // Random number generator

Engr. Farhan Ahmed Umrani Page 52


Object Oriented Programming

// Constructor for a hat


public MagicHat(String hatName) {
this.hatName = hatName; // Store the hat name
rabbits = new Rabbit[1+select.nextInt(maxRabbits)]; // Random rabbits
for(int i = 0; i < rabbits.length; i++) {
rabbits[i] = new Rabbit(); // Create the rabbits
}
}
// String representation of a hat
public String toString() {
// Hat name first...
String hatString = “\n” + hatName + “ contains:\n”;
for(Rabbit rabbit : rabbits) {
hatString += “ “ + rabbit; // Add the rabbits strings
}
return hatString;
}
private String hatName; // Name of the hat
private Rabbit rabbits[]; // Rabbits in the hat
// Nested class to define a rabbit
static class Rabbit
{
// Definition of the Rabbit class...
}
}

Here’s what you need to add for the Rabbit class definition:

public class MagicHat {


// Definition of the MagicHat class – as before...
// Nested class to define a rabbit
static class Rabbit {
// A name is a rabbit name from rabbitNames followed by an integer
static private String[] rabbitNames = {“Floppsy”, “Moppsy”,“Gnasher”, “Thumper”};
static private int[] rabbitNamesCount = new int[rabbitNames.length];
private String name; // Name of the rabbit
// Constructor for a rabbit
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;
}
}

Engr. Farhan Ahmed Umrani Page 53


Object Oriented Programming

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:

public class TryNestedClass


{
static public void main(String[] args)
{
// Create three magic hats and output them
System.out.println(new MagicHat(“Gray Topper”));
System.out.println(new MagicHat(“Black Topper”));
System.out.println(new MagicHat(“Baseball Cap”));
}
}
When I ran the program, I got the following output:

Gray Topper contains:


Floppsy1 Moppsy1 Gnasher1 Floppsy2 Thumper1
Black Topper contains:
Moppsy2 Gnasher2 Floppsy3 Floppsy4

Engr. Farhan Ahmed Umrani Page 54


Object Oriented Programming

Baseball Cap contains:


Moppsy3

You are likely to get something different.


Using a Non-Static Nested Class:
In the previous example, you could make the Rabbit class non-static by deleting the keyword
static from its definition. However, if you try that, the program will no longer compile and
run. The problem is the static data members rabbitNames and rabbitNamesCount in the
Rabbit class. You saw earlier that a non-static nested class cannot have static members, so
you must find an alternative way of dealing with names if you want to make Rabbit a non-
static 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.

Accessing the Top-Level Class Members


You need to modify the class definition to the following:

public class MagicHat {


static int maxRabbits = 5; // Maximuum rabbits in a hat
static Random select = new Random(); // Random number generator
static private String[] rabbitNames = {“Floppsy”, “Moppsy”, “Gnasher”, “Thumper”};
static private int[] rabbitNamesCount = new int[rabbitNames.length];
// Constructor for a hat
public MagicHat(final String hatName) {
this.hatName = hatName; // Store the hat name
rabbits = new Rabbit[1+select.nextInt(maxRabbits)]; // Random rabbits
for(int i = 0; i < rabbits.length; i++) {
rabbits[i] = new Rabbit(); // Create the rabbits
}
}
// String representation of a hat
public String toString()
{
// Hat name first...
String hatString = “\n” + hatName + “ contains:\n”;
for(Rabbit rabbit : rabbits) {
hatString += “ “ + rabbit; // Add the rabbits strings
}
return hatString;
}
private String hatName; // Name of the hat
private Rabbit rabbits[]; // Rabbits in the hat
// Nested class to define a rabbit
class Rabbit {
private String name; // Name of the rabbit
// Constructor for a rabbit
Engr. Farhan Ahmed Umrani Page 55
Object Oriented Programming

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;
}
}
}

Local Nested Classes:


You can define a class inside a method—where it is called a local nested class. It is also
referred to as a local inner class, since a non-static nested class is often referred to as an
inner class. You can create objects of a local inner class only locally—that is, within the
method in which the class definition appears. This is useful when the computation in a
method requires the use of a specialized class that is not required or used elsewhere.
A local inner class can refer to variables declared in the method in which the definition
appears, but only if they are final.

The finalize() Method:


You have the option of including a method finalize() in a class definition. This method is
called automatically by Java before an object is finally destroyed and the space it occupies in
memory is released. In practice this may be some time after the object is inaccessible in your
program. When an object goes out of scope, it is dead as far as your program is concerned,
but the Java Virtual Machine may not get around to disposing of the remains until later.
When it does, it calls the finalize() method for the object. The form of the finalize() method
is:

protected void finalize()


{
// Your clean-up code...
}

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

Engr. Farhan Ahmed Umrani Page 56


Object Oriented Programming

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:

public native long getData(); // Declare a method that is not in Java

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

System.out.println(“7.5 to the power 0 is “ + power(7.5,0));


System.out.println(“10 to the power -2 is “ + power(10,-2));
}
// Raise x to the power n
static double power(double x, int n) {
if(n > 1)
return x*power(x, n-1); // Recursive call
else if(n < 0)
return 1.0/power(x, -n); // Negative power of x
else
return n == 0 ? 1.0 : x; // When n is 0 return 1, otherwise x
}
}

This program will produce the following output:


5.0 to the power 4 is 625.0
7.5 to the power 5 is 23730.46875
7.5 to the power 0 is 1.0
10 to the power -2 is 0.01

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.

Engr. Farhan Ahmed Umrani Page 58


Object Oriented Programming

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.

Using Existing Classes:


A very important part of object-oriented programming allows you to create a new class based
on a class that has already been defined. The class that you use as the base for your new class
can be
one that you have defined, a standard class in Java, or a class defined by someone else—
perhaps
from a package supporting a specialized application area.
This lab focuses on how you can reuse existing classes by creating new classes based on the
ones you have and explores the ramifications of using this facility, and the additional
capabilities it provides.

Engr. Farhan Ahmed Umrani Page 59


Object Oriented Programming

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:

class Spaniel extends Dog


{
// Members of the Spaniel class...
}

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,

Engr. Farhan Ahmed Umrani Page 60


Object Oriented Programming

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.

Hidden Data Members:


You can define a data member in a derived class with the same name as a data member in the
base class. This is not a recommended approach to class design generally, but it’s possible
that it can arise unintentionally. When it occurs, the base class data member may still be
inherited, but will be hidden by the derived class member with the same name. The hiding
mechanism applies regardless of whether the respective types or access attributes are the
same or not—the base class member will be hidden in the derived class if the names are the
same. Any use of the derived class member name will always refer to the member defined as
part of the derived class. To refer to the inherited base class member, you must qualify it with
the keyword super to indicate it is the member of the superclass that you want. Suppose you
have a data member value as a member of the base class, and a data member with the same
name in the derived class. In the derived class, the name value references the derived
class member, and the name super.value refers to the member inherited from the base
class.

Engr. Farhan Ahmed Umrani Page 61


Object Oriented Programming

*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.

Objects of a Derived Class:


An object of a subclass will contain all the members of the original base class, plus any new
members that you have defined in the derived class.

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);

Engr. Farhan Ahmed Umrani Page 62


Object Oriented Programming

}
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:

public class Dog extends Animal {


// constructors for a Dog object
private String name; // Name of a Dog
private String breed; // Dog breed
}

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.

Derived Class Constructors:


You can define two constructors for the subclass Dog, one that just accepts an argument for
the name of a dog and another that accepts both a name and the breed of the Dog object. For
any derived class object, you need to make sure that the private base class member, type, is
properly initialized. You do this by calling a base class constructor from the derived class
constructor:

public class Dog extends Animal {


public Dog(String aName) {
super(“Dog”); // Call the base constructor
name = aName; // Supplied name
breed = “Unknown”; // Default breed value
}

public Dog(String aName, String aBreed) {


super(“Dog”); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed

Engr. Farhan Ahmed Umrani Page 63


Object Oriented Programming

}
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

Testing a Derived Class:


You can try out the Dog class with the following code:
public class TestDerived {
public static void main(String[] args) {
Dog aDog = new Dog(“Fido”, “Chihuahua”); // Create a dog
Dog starDog = new Dog(“Lassie”); // Create a Hollywood dog
System.out.println(aDog); // Let’s hear about it
System.out.println(starDog); // and the star
}
}
Of course, the files containing the Dog and Animal class definition must be in the same
directory as TestDerived.java. The example produces the following rather uninformative
output:
This is a Dog
This is a Dog

Overriding a Base Class Method:


You can define a method in a derived class that has the same signature as a method in the
base class. The access attribute for the method in the derived class can be the same as that in
the base class or less restrictive, but it cannot be more restrictive. This means that if you
declare a method as public in the base class, for example, any derived class definition of the
method must also be declared as public. You cannot omit the access attribute in the derived
class in this case, or specify it as private or protected. When you define a new version of a
base class method in this way, the derived class method will be called for a derived class
object, not the method inherited from the base class. The method in the derived class
overrides the method in the base class. The base class method is still there though, and it is
still possible to call it in a derived class. Let’s see an overriding method in a derived class in
action.

You can add the definition of a new version of toString() to the definition of the derived
class, Dog:

// Present a dog’s details as a string


public String toString()
{
return “It’s “ + name + “ the “ + breed;
}
With this change to the example, the output will now be:

Engr. Farhan Ahmed Umrani Page 64


Object Oriented Programming

It’s Fido the Chihuahua


It’s Lassie the Unknown

Calling a Base Class Method from a Derived Class:


You can rewrite the derived class version of toString() to call the base method:

// Present a dog’s details as a string


public String toString() {
return super.toString() + “\nIt’s “ + name + “ the “ + breed;
}
Running the example again will produce the following output:
This is a Dog
It’s Fido the Chihuahua
This is a Dog
It’s Lassie the Unknown

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.

Engr. Farhan Ahmed Umrani Page 65


Object Oriented Programming

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

Engr. Farhan Ahmed Umrani Page 66


Object Oriented Programming

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.

public class Animal


{
Animal createCreature() {
// Code to create an Animal object and return a reference to it...
}
// Rest of the class definition...
}

You can redefine the createCreature() method in a derived class Dog like this:

public class Dog extends Animal {


Dog createCreature() {
// Code to create a Dog object and return a reference to it...
}
// Rest of the class definition...
}

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:

public class Dog extends Animal {


// A barking method
public void sound() {
System.out.println(“Woof Woof”);
}
// Rest of the class as before...
}

Engr. Farhan Ahmed Umrani Page 67


Object Oriented Programming

You can also derive a class Cat from the class Animal:

public class Cat extends Animal {


public Cat(String aName) {
super(“Cat”); // Call the base constructor
name = aName; // Supplied name
breed = “Unknown”; // Default breed value
}
public Cat(String aName, String aBreed) {
super(“Cat”); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed
}
// Return a String full of a cat’s details
public String toString() {
return super.toString() + “\nIt’s “ + name + “ the “ + breed;
}
// A miaowing method
public void sound() {
System.out.println(“Miiaooww”);
}
private String name; // Name of a cat
private String breed; // Cat breed
}

Just to make it a crowd, you can derive another class—of ducks:

public class Duck extends Animal {


public Duck(String aName) {
super(“Duck”); // Call the base constructor
name = aName; // Supplied name
breed = “Unknown”; // Default breed value
}
public Duck(String aName, String aBreed) {
super(“Duck”); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed
}
// Return a String full of a duck’s details
public String toString() {
return super.toString() + “\nIt’s “ + name + “ the “ + breed;
}
// A quacking method
public void sound() {
System.out.println(“Quack quackquack”);
}
private String name; // Duck name

Engr. Farhan Ahmed Umrani Page 68


Object Oriented Programming

private String breed; // Duck breed


}

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 {

// Rest of the class as before...

// Dummy method to be implemented in the derived classes

public void sound(){}

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;

public class TryPolymorphism {

public static void main(String[] args) {

// Create an array of three different animals

Animal[] theAnimals = {

new Dog(“Rover”, “Poodle”),

new Cat(“Max”, “Abyssinian”),

new Duck(“Daffy”,”Aylesbury”)

};

Animal petChoice; // Choice of pet

Random select = new Random(); // Random number generator

// Make five random choices of pet

Engr. Farhan Ahmed Umrani Page 69


Object Oriented Programming

for(int i = 0; i < 5; i++) {

// Choose a random animal as a pet

petChoice = theAnimals[select.nextInt(theAnimals.length)];

System.out.println(“\nYour choice:\n” + petChoice);

petChoice.sound(); // Get the pet’s reaction

When I ran this I got the following output:

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:

Engr. Farhan Ahmed Umrani Page 70


Object Oriented Programming

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.

 Write a program in java using polymorphism.

 Write a program by using multiple level of inheritance.

Engr. Farhan Ahmed Umrani Page 71


Object Oriented Programming

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:

public abstract class Animal {


public abstract void sound(); // Abstract method
public Animal(String aType) {
type = new String(aType);
}
public String toString() {
return “This is a “ + type;
}
private String type;
}

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

Engr. Farhan Ahmed Umrani Page 72


Object Oriented Programming

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:

Animal thePet = null; // Declare a variable of type Animal

just as you did in the TryPolymorphism class. You can then use this variable to store objects
of the subclasses,

Dog, Spaniel, Duck, and Cat.


When you derive a class from an abstract base class, you don’t have to define all the abstract
methods in the subclass. In this case the subclass will also be abstract and you won’t be able
to instantiate any objects of the subclass either. If a class is abstract, you must use the abstract
keyword when you define it, even if it only inherits an abstract method from its superclass.
Sooner or later you must have a subclass that contains no abstract methods. You can then
create objects of this class type.

In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike{

abstract void run();

class Honda4 extends Bike{

void run(){System.out.println("running safely..");}

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

Understanding the real scenario of abstract class:


In this example, Shape is the abstract class, its implementation is provided by the Rectangle
and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the
end user) and object of the implementation class is provided by the factory method.

Engr. Farhan Ahmed Umrani Page 73


Object Oriented Programming

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.

abstract class Shape{

abstract void draw();

//In real scenario, implementation is provided by others i.e. unknown by end user

class Rectangle extends Shape{

void draw(){System.out.println("drawing rectangle");}

class Circle1 extends Shape{

void draw(){System.out.println("drawing circle");}

//In real scenario, method is called by programmer or user

class TestAbstraction1{

public static void main(String args[]){

Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape()
method

s.draw();

Another example of abstract class in java:


abstract class Bank{

abstract int getRateOfInterest();

Engr. Farhan Ahmed Umrani Page 74


Object Oriented Programming

class SBI extends Bank{

int getRateOfInterest(){return 7;}

class PNB extends Bank{

int getRateOfInterest(){return 8;}

class TestBank{

public static void main(String args[]){

Bank b;

b=new SBI();

System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");

b=new PNB();

System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");

Abstract class having constructor, data member, methods etc.


An abstract class can have data member, abstract method, method body, constructor and even
main() method.

//example of abstract class that have method body

abstract class Bike{

Bike(){System.out.println("bike is created");}

abstract void run();

void changeGear(){System.out.println("gear changed");}

class Honda extends Bike{

Engr. Farhan Ahmed Umrani Page 75


Object Oriented Programming

void run(){System.out.println("running safely..");}

class TestAbstraction2{

public static void main(String args[]){

Bike obj = new Honda();

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

compile time error

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.

The Universal Superclass:


I must now reveal something I have been keeping from you. All the classes that you define
are subclasses by default—whether you like it or not. All your classes have a standard class,
Object, as a base, so Object is a superclass of every class. You never need to specify the class
Object as a base in the definition of your classes—it happens automatically. There are some
interesting consequences of having Object as a universal superclass. For one thing, a variable
of type Object can store a reference to an object of any class type. This is useful when you
want to write a method that needs to handle objects of unknown type. You can define a
parameter to the method of type Object, in which case a reference to any type of object can
be passed to the method. When necessary you can include code in the method to figure out
what kind of object it actually is (you’ll see some of the tools that will enable you to do this a
little later in this chapter). Of course, your classes will inherit members from the class Object.
These all happen to be methods, of which seven are public, and two are protected. The seven
public methods are:

Engr. Farhan Ahmed Umrani Page 76


Object Oriented Programming

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.

Engr. Farhan Ahmed Umrani Page 77


Object Oriented Programming

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:

Spaniel aPet = new Spaniel(“Fang”);


Animal theAnimal = (Animal)aPet; // Cast the Spaniel to Animal

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:

Animal theAnimal = aPet; // Cast the Spaniel to Animal

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.

Engr. Farhan Ahmed Umrani Page 78


Object Oriented Programming

LAB # 11

Interfaces & Nested interfaces


Objective:
 How to make & use of interfaces/nested interfaces in java programs.

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.

Engr. Farhan Ahmed Umrani Page 79


Object Oriented Programming

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.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve fully abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

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.

Understanding relationship between classes and interfaces:


As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.

Engr. Farhan Ahmed Umrani Page 80


Object Oriented Programming

Simple example of Java interface:


In this example, Printable interface have only one method, its implementation is provided in the A
class.
interface printable{  
void print();  
}  

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

Multiple inheritance in Java by interface:


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.

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

Q) Multiple inheritances is not supported through class in java but it is


possible by interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in


case of class. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:
interface Printable{  
void print();  
}  
interface Showable{  
void print();  
}  
  
class TestTnterface1 implements Printable,Showable{  
public void print(){System.out.println("Hello");}  
public static void main(String args[]){  
TestTnterface1 obj = new TestTnterface1();  
obj.print();  
 }  
}  
Output:Hello

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{  

Engr. Farhan Ahmed Umrani Page 83


Object Oriented Programming

  
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

Q) What is marker or tagged interface?


An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.

//How Serializable interface is written?  
public interface Serializable{  
}  

Java Nested Interface


An interface i.e. declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.

Points to remember for nested interfaces

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.

Syntax of nested interface which is declared within the interface

1. interface interface_name{  

Engr. Farhan Ahmed Umrani Page 84


Object Oriented Programming

2.  ...  
3.  interface nested_interface_name{  
4.   ...  
5.  }  
6. }   

Syntax of nested interface which is declared within the class

1. class class_name{  
2.  ...  
3.  interface nested_interface_name{  
4.   ...  
5.  }  
6. }   

Example of nested interface which is declared within the interface

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

Engr. Farhan Ahmed Umrani Page 85


Object Oriented Programming

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. }  

Example of nested interface which is declared within the class

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

Can we define a class inside the interface?

Engr. Farhan Ahmed Umrani Page 86


Object Oriented Programming

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.

Engr. Farhan Ahmed Umrani Page 87


Object Oriented Programming

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:

Season now = Season.winter;


if(now.equals(Season.winter))
System.out.println(“It is definitely winter!”);

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:

Engr. Farhan Ahmed Umrani Page 88


Object Oriented Programming

if(now.compareTo(Season.summer) > 0)
System.out.println(“It is definitely getting colder!”);

Adding Members to an Enumeration Class


Because an enumeration is a class, you have the possibility to add your own methods and
fields when you define the enumeration type. You can also add your own constructors to
initialize any additional fields you introduce. Let’s take an example. Suppose you want to
define an enumeration for clothing sizes—jackets, say. Your initial definition might be like
this:

public enum JacketSize { small, medium, large, extra_large, extra_extra_large }

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:

public enum JacketSize { small(36), medium(40),


large(42),extra_large(46),extra_extra_large(48);
// Constructor
JacketSize(int csize) {
this.csize = csize;
}
// Method to return the csize for the current jacket size
public int csize() {
return csize;
}
private int csize; // Field to record size
}
Note how the list of enumeration constants now ends with a semicolon. Each constant in the
list has the corresponding csize between parentheses, and this value will be passed to the
constructor that you have added to the class. In the previous definition of JacketSize, the
appearance of each enumeration constant results in a call to the default constructor for the
class. In fact, you could put an empty pair of parentheses after the name of each constant, and
it would still compile. However, this would not improve the clarity of the code. Because you
have defined a constructor, no default destructor will be defined for the enumeration class, so
you cannot write enumeration constants just as names. You must put the parentheses
enclosing a value for the csize following each enumeration constant. Of course, if you wanted
to have the option of omitting the csize for some of the constants in the enumeration, you
could define your own default constructor and assign a default value for the csize field. Even
though you have added your own constructor, the fields inherited from the base class, Enum,
that store the name of the constant and its ordinal value, will still be set appropriately. The
ordering of the constants that compareTo() implements will still be determined by the
sequence in which the constants appear in the definition. Note that you must not declare a
constructor in an enumeration class as public.
If you do, the enum class definition will not compile. The only modifier that you are allowed
to apply to a constructor in class defining an enumeration is private, which will result in the

Engr. Farhan Ahmed Umrani Page 89


Object Oriented Programming

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:

public enum JacketColor { red, orange, yellow, blue, green }

This should be in a file with the name JacketColor.java.


Now you can define a class that represents a jacket:

public class Jacket {


public Jacket(JacketSize size, JacketColor color) {
this.size = size;
this.color = color;
}
public String toString() {
StringBuffer str = new StringBuffer(“Jacket “);
return str.append(size).append(“ in “).append(color).toString();
}
private JacketSize size;
private JacketColor color;
}
Finally, you need a file containing code to try out some jackets:
public class TryEnumeration {
public static void main(String[] args) {
// Define some jackets
Jacket[] jackets = { new Jacket(JacketSize.medium, JacketColor.red),
new Jacket(JacketSize.extra_large, JacketColor.yellow),
new Jacket(JacketSize.small, JacketColor.green),
new Jacket(JacketSize.extra_extra_large, JacketColor.blue)
};
// Output colors available
System.out.println(“Jackets colors available are:\n”);
for(JacketColor color: JacketColor.values()) {
System.out.print(“ “ + color);
}
// Output sizes available
System.out.println(“\n\nJackets sizes available are:\n”);
for(JacketSize size: JacketSize.values()) {
System.out.print(“ “ + size);
}
System.out.println(“\n\nJackets in stock are:”);
for(Jacket jacket: jackets) {
Engr. Farhan Ahmed Umrani Page 90
Object Oriented Programming

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.

To achieve encapsulation in Java −

 Declare the variables of a class as private.

 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 −

/* File name : EncapTest.java */


public class EncapTest {
private String name;
private String idNum;
private int age;

Engr. Farhan Ahmed Umrani Page 91


Object Oriented Programming

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge( int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}

public void setIdNum( String newId) {


idNum = newId;
}
}

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 −

Engr. Farhan Ahmed Umrani Page 92


Object Oriented Programming

/* File name : RunEncap.java */


public class RunEncap {

public static void main(String args[]) {


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());


}
}

This will produce the following result −

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.

Engr. Farhan Ahmed Umrani Page 94


Object Oriented Programming

LAB # 13

Java Collections
Objective:
 How to make & use of java collections in java programs.

Java Collections- List:


List Implementations
Being a Collection subtype all methods in the Collection interface are also available in
the List interface.

Since List is an interface you need to instantiate a concrete implementation of the interface


in order to use it. You can choose between the following List implementations in the Java
Collections API:

 java.util.ArrayList
 java.util.LinkedList
 java.util.Vector
 java.util.Stack

There are also List implementations in the java.util.concurrent package, but I will


leave the concurrency utilities out of this tutorial.

Here are a few examples of how to create a List instance:

List listA = new ArrayList();


List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();

Adding and Accessing Elements


To add elements to a List you call its add() method. This method is inherited from
the Collectioninterface. Here are a few examples:

Engr. Farhan Ahmed Umrani Page 95


Object Oriented Programming

List listA = new ArrayList();

listA.add("element 1");
listA.add("element 2");
listA.add("element 3");

listA.add(0, "element 0");

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:

List listA = new ArrayList();

listA.add("element 0");
listA.add("element 1");
listA.add("element 2");

//access via index


String element0 = listA.get(0);
String element1 = listA.get(1);
String element3 = listA.get(2);

//access via Iterator


Iterator iterator = listA.iterator();
while(iterator.hasNext(){
String element = (String) iterator.next();
}

//access via new for-loop


for(Object object : listA) {
String element = (String) object;
}

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.

Engr. Farhan Ahmed Umrani Page 96


Object Oriented Programming

Removing Elements
You can remove elements in two ways:

1. remove(Object element)
2. remove(int index)

remove(Object element) removes that element in the list, if it is present. All subsequent


elements in the list are then moved up in the list. Their index thus decreases by 1.

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 list = new ArrayList();

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 list = new ArrayList();

list.add("object 1");
list.add("object 2");

int size = list.size();

Engr. Farhan Ahmed Umrani Page 97


Object Oriented Programming

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:

List<MyObject> list = new ArrayList<MyObject>();

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:

MyObject myObject = list.get(0);

for(MyObject anObject : list){


//do someting to anObject...
}

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:

List list = new ArrayList();

//add elements to list

Iterator iterator = list.iterator();


while(iterator.hasNext()) {
Object next = iterator.next();
}

You obtain an Iterator by calling the iterator() method of the List interface.

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.

Inside the while loop you call the next() method of the Iterator interface to obtain the


next element pointed to by the Iterator.

Engr. Farhan Ahmed Umrani Page 98


Object Oriented Programming

If the List is typed you can save some object casting inside the while loop. Here is an
example:

List<String> mylistStr = new ArrayList<>();

Iterator<String> iterator = mylistStr.iterator();


while(iterator.hasNext()){
String obj = iterator.next();
}

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:

List list = new ArrayList();

//add elements to list

for(Object obj : list) {

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:

List<String> list = new ArrayList<String>();

//add elements to list

for(String obj : list) {

Notice how the List is typed to String. Therefore you can set the type of the variable inside
the for loop to String.

The last way to iterate a List is to use a standard for loop like this:

List list = new ArrayList();

Engr. Farhan Ahmed Umrani Page 99


Object Oriented Programming

//add elements to list

for(int i=0; i < list.size(); i++) {


Object obj = list.get(i);
}

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.

Inside the for loop the example accesses the elements in the List via its get() method,


passing the incrementing variable i as parameter.

Java Collections – Stack:


The java.util.Stack class deserves a little explanation on its own. In the text on
the List interface the Stack class is listed as an implementation. The typical use of a Stack is
not as a List though.

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.

Here is a Stack usage example:

Stack stack = new Stack();

stack.push("1");

stack.push("2");

stack.push("3");

//look at top object ("3"), without taking it off the stack.

Object objTop = stack.peek();

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 push() method pushes an object onto the top of the Stack.

Engr. Farhan Ahmed Umrani Page 100


Object Oriented Programming

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.

Searching the Stack


You can search for an object on the stack to get it's index, using the search() method. The
object's equals() method is called on every object on the Stack to determine if the searched-
for object is present on the Stack. The index you get is the index from the top of the Stack,
meaning the top element on the Stack has index 1.

Here is how you search a Stack for an object:

Stack stack = new Stack();

stack.push("1");

stack.push("2");

stack.push("3");

int index = stack.search("3"); //index = 1

Java Collections – Queue:


Queue Implementations
Being a Collection subtype all methods in the Collection interface are also available in
the Queue interface.

Since Queue is an interface you need to instantiate a concrete implementation of the interface


in order to use it. You can choose between the following Queue implementations in the Java
Collections API:

 java.util.LinkedList

 java.util.PriorityQueue

LinkedList is a pretty standard queue implementation.

Engr. Farhan Ahmed Umrani Page 101


Object Oriented Programming

PriorityQueue stores its elements internally according to their natural order (if they
implement Comparable), or according to a Comparator passed to the PriorityQueue.

There are also Queue implementations in the java.util.concurrent package, but I will leave the


concurrency utilities out of this tutorial.

Here are a few examples of how to create a Queue instance:

Queue queueA = new LinkedList();

Queue queueB = new PriorityQueue();

Adding and Accessing Elements


To add elements to a Queue you call its add() method. This method is inherited from
the Collection interface. Here are a few examples:

Queue queueA = new LinkedList();

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:

Object firstElement = queueA.element();

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:

Queue queueA = new LinkedList();

queueA.add("element 0");

queueA.add("element 1");

Engr. Farhan Ahmed Umrani Page 102


Object Oriented Programming

queueA.add("element 2");

//access via Iterator

Iterator iterator = queueA.iterator();

while(iterator.hasNext(){

String element = (String) iterator.next();

//access via new for-loop

for(Object object : queueA) {

String element = (String) object;

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.

Here is a remove example();

Object firstElement = queueA.remove();

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:

Queue<MyObject> queue = new LinkedList<MyObject>();

Engr. Farhan Ahmed Umrani Page 103


Object Oriented Programming

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:

MyObject myObject = queue.remove();

for(MyObject anObject : queue){

//do someting to anObject...

Assignment:
 Practice all above programs and take snapshot of outputs.

Engr. Farhan Ahmed Umrani Page 104


Object Oriented Programming

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.

Engr. Farhan Ahmed Umrani Page 105


Object Oriented Programming

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.

Note: At a time one thread is executed only.

Life cycle of a Thread (Thread States)

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

Engr. Farhan Ahmed Umrani Page 106


Object Oriented Programming

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

Engr. Farhan Ahmed Umrani Page 107


Object Oriented Programming

A thread is in terminated or dead state when its run() method exits.

How to create thread:


There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

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.

Commonly used Constructors of Thread class:


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.

Engr. Farhan Ahmed Umrani Page 108


Object Oriented Programming

15. public void suspend(): is used to suspend the thread(depricated).


16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

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:

 A new thread starts(with new callstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class:


1. class Multi extends Thread{  
2. public void run(){  
3. System.out.println("thread is running...");  
4. }  
5. public static void main(String args[]){  
6. Multi t1=new Multi();  
7. t1.start();  
8.  }  
9. }  

Output:thread is running...

2) Java Thread Example by implementing Runable interface:


1. class Multi3 implements Runnable{  

Engr. Farhan Ahmed Umrani Page 109


Object Oriented Programming

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.

Thread Scheduler in Java


Thread scheduler in java is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.

Difference between pre-emptive scheduling and time slicing

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.

Sleep method in java


The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Engr. Farhan Ahmed Umrani Page 110


Object Oriented Programming

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throws InterruptedException


o public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java


1. class TestSleepMethod1 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.   TestSleepMethod1 t1=new TestSleepMethod1();  
10.   TestSleepMethod1 t2=new TestSleepMethod1();  
11.    
12.   t1.start();  
13.   t2.start();  
14.  }  
15. }  

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

Engr. Farhan Ahmed Umrani Page 111


Object Oriented Programming

Can we start a thread twice


No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for second
time, it will throw exception.

Let's understand it by the example given below:

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

What if we call run() method directly instead start() method?

o Each thread starts in a separate call stack.


o Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.

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. }  

Engr. Farhan Ahmed Umrani Page 112


Object Oriented Programming

Test it Now
Output:running...

Problem if you direct call run() method

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.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking. But we use multithreading than
multiprocessing because threads share a common memory area. They don't allocate separate
memory area so saves memory, and context-switching between the threads takes less time
than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

2) You can perform many operations together so it saves time.

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)

1) Process-based Multitasking (Multiprocessing)

 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.

2) Thread-based Multitasking (Multithreading)

Engr. Farhan Ahmed Umrani Page 114


Object Oriented Programming

 Threads share the same address space.


 Thread is lightweight.
 Cost of communication between the thread is low.

Note: At least one process is required for each thread.

Assignment:
 Practice all above programs and take snapshot of outputs.

LAB # 15
Exception Handling in Java
Objective:
 How to handle exception in java programs.

Exception Handling in Java:


The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

In this page, we will learn about java exception, its type and the difference between checked
and unchecked exceptions.

Engr. Farhan Ahmed Umrani Page 115


Object Oriented Programming

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.

What is exception handling?


Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO,
SQL, Remote etc.

Advantage of Exception Handling?


The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why we
use exception handling. Let's take a scenario:

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.

Hierarchy of Java Exception classes

Engr. Farhan Ahmed Umrani Page 116


Object Oriented Programming

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

Difference between checked and unchecked exceptions

1) Checked Exception

Engr. Farhan Ahmed Umrani Page 117


Object Oriented Programming

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.

Common scenarios where exceptions may occur


There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException  

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.

1. String s=null;  
2. System.out.println(s.length());//NullPointerException  

3) Scenario where NumberFormatException occurs


The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.

1. String s="abc";  

Engr. Farhan Ahmed Umrani Page 118


Object Oriented Programming

2. int i=Integer.parseInt(s);//NumberFormatException  

4) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];  
2. a[10]=50; //ArrayIndexOutOfBoundsException  

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.

1. try
2. catch
3. finally
4. throw
5. throws

Java try-catch

Java try block


Java try block is used to enclose the code that might throw an exception. It must be used
within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

try{  

//code that may throw exception  

}catch(Exception_class_Name ref){}  

Syntax of try-finally block


Engr. Farhan Ahmed Umrani Page 119
Object Oriented Programming

try{  

//code that may throw exception  

}finally{}  

Java catch block


Java catch block is used to handle the Exception. It must be used after the try block only.

You can use multiple catch block with a single try.

Problem without exception handling


Let's try to understand the problem if we don't use try-catch block.

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:

Exception in thread main java.lang.ArithmeticException:/ by zero

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.

Engr. Farhan Ahmed Umrani Page 120


Object Oriented Programming

Solution by exception handling


Let's see the solution of above problem by java try-catch block.

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:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

Engr. Farhan Ahmed Umrani Page 121


Object Oriented Programming

Internal working of java try-catch block

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:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.

Engr. Farhan Ahmed Umrani Page 122


Object Oriented Programming

Java catch multiple exceptions


Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.

Let's see a simple example of 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];  

Engr. Farhan Ahmed Umrani Page 123


Object Oriented Programming

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

Java Nested try block


The try block within a try block is known as nested try block in java.

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.

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.     }  

Engr. Farhan Ahmed Umrani Page 124


Object Oriented Programming

14. }  
15. catch(Exception e)  
16. {  
17. }  
18. ....  

Java nested try example


Let's see a simple example of java nested try block.

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.

Engr. Farhan Ahmed Umrani Page 125


Object Oriented Programming

LAB # 16

Java Exception Handling Keywords


Objective:
 How to make & use of exception handling keyword in java programs.

Java finally block:


Java finally block is a block that is used to execute important code such as closing
connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Engr. Farhan Ahmed Umrani Page 126


Object Oriented Programming

Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
any).

Why use java finally


Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.

Usage of Java finally


Let's see the different cases where java finally block can be used.

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[]){  

Engr. Farhan Ahmed Umrani Page 127


Object Oriented Programming

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...

Engr. Farhan Ahmed Umrani Page 128


Object Oriented Programming

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).

Java Exception propagation


An exception is first thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method,If not caught there, the exception again
drops down to the previous method, and so on until they are caught or until they reach
the very bottom of the call stack.This is called exception propagation.

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Program of Exception Propagation

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...

Engr. Farhan Ahmed Umrani Page 129


Object Oriented Programming

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).

Program which describes that checked exceptions are not 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

Output:Compile Time Error

ExceptionHandling with MethodOverriding in Java


There are many rules if we talk about methodoverriding with exception handling. The
Rules are as follows:

o If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but it can declare
unchecked exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden
method can declare same, subclass exception or no exception but cannot
declare parent exception.

If the superclass method does not declare an exception

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.   }  

Engr. Farhan Ahmed Umrani Page 131


Object Oriented Programming

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

If the superclass method declares an exception

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.

Example in case subclass overridden method declares parent


exception

Engr. Farhan Ahmed Umrani Page 132


Object Oriented Programming

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

Example in case subclass overridden method declares same exception

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

Example in case subclass overridden method declares subclass


exception

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

Example in case subclass overridden method declares no exception

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();  

Engr. Farhan Ahmed Umrani Page 134


Object Oriented Programming

13.    }catch(Exception e){}  
14.   }  
15. }  
Test it Now
Output:child

Java Custom Exception


If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

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

Output:Exception occured: InvalidAgeException:not valid


rest of the code...

Assignment:
 Practice all above programs and take snapshot of outputs.

Engr. Farhan Ahmed Umrani Page 136


Object Oriented Programming

Introduction to GUI Building

Designing a Swing GUI in NetBeans IDE

Handling Images in a Java GUI Application

Note: The above topics are not included in lab manual but all these topics
can be covered by presentation or by home assignment.

Introduction to GUI Building


This beginner tutorial teaches you how to create a simple graphical user interface and add simple back-end
functionality. In particular we will show how to code the behavior of buttons and fields in a Swing form.
We will work through the layout and design of a GUI and add a few buttons and text fields. The text fields will be
used for receiving user input and also for displaying the program output. The button will initiate the functionality
built into the front end. The application we create will be a simple but functional calculator.

Engr. Farhan Ahmed Umrani Page 137


Object Oriented Programming
For a more comprehensive guide to the GUI Builder's design features, including video demonstrations of the
various design features.

Contents

 Exercise 1: Creating a Project


 Exercise 2: Building the Front End
 Exercise 3: Adding Functionality
 Exercise 4: Running the Program
 How Event Handling Works

To complete this tutorial, you need the following software and resources.
Software or Resource Version Required

NetBeans IDE with Java SE version 6.9 or higher

Java Development Kit (JDK) version 6, 7 or 8

Exercise 1: Creating a Project


The first step is to create an IDE project for the application that we are going to develop. We will name our
project NumberAddition.
1. Choose File > New Project. Alternatively, you can click the New Project icon in the IDE toolbar.

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.

Exercise 2: Building the Front End


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. We will place the
container in a new package, which will appear within the Source Packages node.
Create a JFrame container
1. In the Projects window, right-click the NumberAddition node and choose New > Other.

2. In the New File dialog box, choose the Swing GUI Forms category and the JFrame Form file
type. Click Next.

Engr. Farhan Ahmed Umrani Page 138


Object Oriented Programming
3. Enter NumberAdditionUI as the class name.

4. Enter my.numberaddition as the package.

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.

Renaming the Components


In this step we are going to rename the display text of the components that were just added to the JFrame.
1. Double-click jLabel1 and change the text property to First Number:.

2. Double-click jLabel2 and change the text to Second Number:.

3. Double-click jLabel3 and change the text to Result:.

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.

7. Rename the display text of jButton3 to Exit.

Your Finished GUI should now look like the following screenshot:

Engr. Farhan Ahmed Umrani Page 139


Object Oriented Programming

Exercise 3: Adding Functionality


In this exercise we are going to give functionality to the Add, Clear, and Exit buttons.
The jTextField1 and jTextField2 boxes will be used for user input and jTextField3 for program
output - what we are creating is a very simple calculator. Let's begin.
Making the Exit Button Work
In order to give function to the buttons, we have to assign an event handler to each to respond to events. In our
case we want to know when the button is pressed, either by mouse click or via keyboard. So we will use
ActionListener responding to ActionEvent.
1. Right click the Exit button. From the pop-up menu choose Events > Action > actionPerformed. Note that
the menu contains many more events you can respond to! When you select
the actionPerformed event, the IDE will automatically add an ActionListener to the Exit button and
generate a handler method for handling the listener's actionPerformed method.
2. The IDE will open up the Source Code window and scroll to where you implement the action you want
the button to do when the button is pressed (either by mouse click or via keyboard). Your Source Code
window should contain the following lines:
3. private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
4. //TODO add your handling code here:
}
5. We are now going to add code for what we want the Exit Button to do. Replace the TODO line
with System.exit(0);. Your finished Exit button code should look like this:

6. private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)


{
7. System.exit(0);
}
Making the Clear Button Work
1. Click the Design tab at the top of your work area to go back to the Form Design.
2. Right click the Clear button (jButton1). From the pop-up menu select Events > Action >
actionPerformed.
3. We are going to have the Clear button erase all text from the jTextFields. To do this, you will add some
code like above. Your finished source code should look like this:
4. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
5. jTextField1.setText("");
6. jTextField2.setText("");
7. jTextField3.setText("");
}
The above code changes the text in all three of our JTextFields to nothing, in essence it is overwriting the
existing Text with a blank.

Engr. Farhan Ahmed Umrani Page 140


Object Oriented Programming

Making the Add Button Work


The Add button will perform three actions.
1. It is going to accept user input from jTextField1 and jTextField2 and convert the input from a
type String to a float.
2. It will then perform addition of the two numbers.
3. And finally, it will convert the sum to a type String and place it in jTextField3.

Lets get started!


1. Click the Design tab at the top of your work area to go back to the Form Design.
2. Right-click the Add button (jButton2). From the pop-up menu, select Events > Action >
actionPerformed.
3. We are going to add some code to have our Add button work. The finished source code shall look like
this:
4. private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
5. // First we define float variables.
6. float num1, num2, result;
7. // We have to parse the text to a type float.
8. num1 = Float.parseFloat(jTextField1.getText());
9. num2 = Float.parseFloat(jTextField2.getText());
10. // Now we can perform the addition.
11. result = num1+num2;
12. // We will now pass the value of result to jTextField3.
13. // At the same time, we are going to
14. // change the value of result from a float to a string.
15. jTextField3.setText(String.valueOf(result));
}
Our program is now complete we can now build and run it to see it in action.

Exercise 4: Running the Program


To run the program in the IDE:
1. Choose Run > Run Project (Number Addition) (alternatively, press F6).
Note: If you get a window informing you that Project NumberAddition does not have a main class set,
then you should select my.NumberAddition.NumberAdditionUI as the main class in the
same window and click the OK button.
To run the program outside of the IDE:
1. Choose Run > Clean and Build Main Project (Shift-F11) to build the application JAR file.
2. Using your system's file explorer or file manager, navigate to the NumberAddition/dist directory.

Note: The location of the NumberAddition project directory depends on the path you specified


while creating the project in step 3 of the Exercise 1: Creating a Project section.
3. Double-click the NumberAddition.jar file.

After a few seconds, the application should start.


Note: If double-clicking the JAR file does not launch the application, see this article for information on setting
JAR file associations in your operating system.
You can also launch the application from the command line.
To launch the application from the command line:
1. On your system, open up a command prompt or terminal window.
2. In the command prompt, change directories to the NumberAddition/dist directory.

Engr. Farhan Ahmed Umrani Page 141


Object Oriented Programming
3. At the command line, type the following statement:
java -jar NumberAddition.jar
Note: Make sure my.NumberAddition.NumberAdditionUI is set as the main class before
running the application. You can check this by right-clicking the NumberAddition project node in the
Projects pane, choosing Properties in the popup menu, and selecting the Run category in the Project
Properties dialog box. The Main Class field should
display my.numberaddition.NumberAdditionUI.

How Event Handling Works


This tutorial has showed how to respond to a simple button event. There are many more events you can have
your application respond to. The IDE can help you find the list of available events your GUI components can
handle:
1. Go back to the file NumberAdditionUI.java in the Editor. Click the Design tab to see the GUI's
layout in the GUI Builder.
2. Right-click any GUI component, and select Events from the pop-up menu. For now, just browse the
menu to see what's there, you don't need to select anything.
3. Alternatively, you can select Properties from the Window menu. In the Properties window, click the
Events tab. In the Events tab, you can view and edit events handlers associated with the currently active
GUI component.

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

Engr. Farhan Ahmed Umrani Page 142


Object Oriented Programming
taking ActionEvent object which is implemented simply by calling
your jButton3ActionPerformed event handler. The button is now listening to action events.
Everytime it is pressed an ActionEvent is generated and passed to the listener's actionPerformed
method which in turn executes code that you provided in the event handler for this event.
Generally speaking, to be able to respond, each interactive GUI component needs to register to an event listener
and needs to implement an event handler. As you can see, NetBeans IDE handles hooking up the event listener
for you, so you can concentrate on implementing the actual business logic that should be triggered by the event.

Designing a Swing GUI in NetBeans IDE

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.

Engr. Farhan Ahmed Umrani Page 143


Object Oriented Programming

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

NetBeans IDE version 6.9 and more recent

Java Development Kit (JDK) version 6, 7 or 8

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.

To create a new ContactEditor application project:


1. Choose File > New Project. Alternately, you can click the New Project
icon in the IDE toolbar.

Engr. Farhan Ahmed Umrani Page 144


Object Oriented Programming

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.

Getting Familiar with the GUI Builder


Now that we've set up a new project for our application, let's take a minute to familiarize ourselves with the GUI
Builder's interface.
Note: To explore the GUI Builder interface with an interactive demo, view the Exploring GUI Builder
(.swf) screencast.

Engr. Farhan Ahmed Umrani Page 145


Object Oriented Programming

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

Engr. Farhan Ahmed Umrani Page 146


Object Oriented Programming
defined relationships between components. Whenever you resize the form, switch locales, or specify a different
look and feel, your GUI automatically adjusts to respect the target look and feel's insets and offsets.
Free Design
In the IDE's GUI Builder, you can build your forms by simply putting components where you want them as though
you were using absolute positioning. The GUI Builder figures out which layout attributes are required and then
generates the code for you automatically. You need not concern yourself with insets, anchors, fills, and so forth.
Automatic Component Positioning (Snapping)
As you add components to a form, the GUI Builder provides visual feedback that assists in positioning
components based on your operating system's look and feel. The GUI Builder provides helpful inline hints and
other visual feedback regarding where components should be placed on your form, automatically snapping
components into position along guidelines. It makes these suggestions based on the positions of the components
that have already been placed in the form, while allowing the padding to remain flexible such that different target
look and feels render properly at runtime.
Visual Feedback
The GUI Builder also provides visual feedback regarding component anchoring and chaining relationships. These
indicators enable you to quickly identify the various positioning relationships and component pinning behavior
that affect the way your GUI will both appear and behave at runtime. This speeds the GUI design process,
enabling you to quickly create professional-looking visual interfaces that work.

First Things First


Now that you have familiarized yourself with the GUI builder's interface, it's time to begin developing the UI of our
ContactEditor application. In this section we'll take a look at using the IDE's Palette to add the various GUI
components that we need to our form.
Thanks to the IDE's Free Design paradigm, you no longer have to struggle with layout managers to control the
size and position of the components within your containers. All you need to do is drag and drop the components
you need to your GUI form as shown in the illustrations that follow.
Note: Refer to the Adding individual and multiple components (.swf) screencast for an interactive demo on the
section below.
Adding Components: The Basics
Though the IDE's GUI Builder simplifies the process of creating Java GUIs, it is often helpful to sketch out the
way you want your interface to look before beginning to lay it out. Many interface designers consider this a "best
practice" technique, however, for the purposes of this tutorial you can simply peek at how our completed form
should look by jumping ahead to the Previewing your GUI section.
Since we've already added a JFrame as our form's top-level container, the next step is to add a couple of
JPanels which will enable us to cluster the components of our UI using titled borders. Refer to the following
illustrations and notice the IDE's "drag and drop" behavior when accomplishing this.

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.

Engr. Farhan Ahmed Umrani Page 147


Object Oriented Programming

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.

To resize the JPanel:


1. Select the JPanel you just added. The small square resize handles
reappear around the component's perimeter.
2. Click and hold the resize handle on the right edge of the JPanel and
drag until the dotted alignment guideline appears near the form's
edge.
3. Release the resize handle to resize the component.
The JPanel component is extended to span between the container's
left and right margins in accordance with the recommended offset, as
shown in the following illustration.

Engr. Farhan Ahmed Umrani Page 148


Object Oriented Programming

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.

Engr. Farhan Ahmed Umrani Page 149


Object Oriented Programming

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.

To add title borders to the JPanels:


1. Select the top JPanel in the GUI Builder.
2. In the Properties window, click the ellipsis button (...) next to the
Border property.
3. In the JPanel Border editor that appears, select the TitledBorder node
in the Available Borders pane.
4. In the Properties pane below, enter Name for the Title property.
5. Click the ellipsis (...) next to the Font property, select Bold for the Font
Style, and enter 12 for the Size. Click OK to exit the dialogs.
6. Select the bottom JPanel and repeat steps 2 through 5, but this time
right-click the JPanel and access the Properties window using the
pop-up menu. Enter E-mail for the Title property.
Titled borders are added to both JPanel components.

Engr. Farhan Ahmed Umrani Page 150


Object Oriented Programming

Adding Individual Components to the Form


Now we need to start adding the components that will present the actual contact information in our contact list. In
this task we'll add four JTextFields that will display the contact information and the JLabels that will describe
them. While accomplishing this, notice the horizontal and vertical guidelines that the GUI Builder displays,
suggesting the preferred component spacing as defined by your operating system's look and feel. This ensures
that your GUI is automatically rendered respecting the target operating system's look and feel at runtime.

To add a JLabel to the form:


1. In the Palette window, select the Label component from the Swing
Controls category.
2. Move the cursor over the Name JPanel we added earlier. When the
guidelines appear indicating that the JLabel is positioned in the top left
corner of the JPanel with a small margin at the top and left edges,
click to place the label.
The JLabel is added to the form and a corresponding node
representing the component is added to the Inspector window.
Before going further, we need to edit the display text of the JLabel we just added. Though you can edit
component display text at any point, the easiest way is to do this as you add them.

To edit the display text of a JLabel:


1. Double-click the JLabel to select its display text.
2. Type First Name: and press Enter.
The JLabel's new name is displayed and the component's width
adjusts as a result of the edit.
Now we'll add a JTextField so we can get a glimpse of the GUI Builder's baseline alignment feature.

To add a JTextField to the form:


1. In the Palette window, select the Text Field component from the
Swing Controls category.

Engr. Farhan Ahmed Umrani Page 151


Object Oriented Programming

2. Move the cursor immediately to the right of the First


Name: JLabel we just added. When the horizontal guideline appears
indicating that the JTextField's baseline is aligned with that of the
JLabel and the spacing between the two components is suggested
with a vertical guideline, click to position the JTextField.
The JTextField snaps into position in the form aligned with the
JLabel's baseline, as shown in the following illustration. Notice that
the JLabel shifted downward slightly in order to align with the taller
text field's baseline. As usual, a node representing the component is
added to the Navigator window.

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.

Engr. Farhan Ahmed Umrani Page 152


Object Oriented Programming

Adding Multiple Components to the Form


Now we'll add the Title: and Nickname: JLabels that describe two JTextFields that we're going to add in a
minute. We'll drag and drop the components while pressing the Shift key, to quickly add them to the form. While
accomplishing this, again notice that the GUI Builder displays horizontal and vertical guidelines suggesting the
preferred component spacing.

To add multiple JLabels to the form:


1. In the Palette window, select the Label component from the Swing
Controls category by clicking and releasing the mouse button.
2. Move the cursor over the form directly below the First
Name: JLabel we added earlier. When the guidelines appear
indicating that the new JLabel's left edge is aligned with that of the
JLabel above and a small margin exists between them, shift-click to
place the first JLabel.
3. While still pressing the Shift key, place another JLabel immediately to
the right of the first. Make certain to release the Shift key prior to
positioning the second JLabel. If you forget to release the Shift key
prior to positioning the last JLabel, simply press the Escape key.
The JLabels are added to the form creating a second row, as shown
in the following illustration. Nodes representing each component are
added to the Navigator window.

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.

To edit the display text of JLabels:


1. Double-click the first JLabel to select its display text.
2. Type Title: and press Enter.
3. Repeat steps 1 and 2, entering Nickname: for the second JLabel's
name property.
The JLabels' new names are displayed in the form and are shifted as
a result of their edited widths, as shown in the following illustration.

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.

To insert a JTextField between two JLabels:


1. In the Palette window, select the Text Field component from the
Swing Controls category.
2. Move the cursor over the Title: and Nickname: JLabels on the
second row such that the JTextField overlaps both and is aligned to
their baselines. If you encounter difficulty positioning the new text
field, you can snap it to the left guideline of the Nickname JLabel as
shown in the first image below.
3. Click to place the JTextField between
the Title: and Nickname: JLabels.
The JTextField snaps into position between the two JLabels. The
rightmost JLabel shifts toward the right of the JTextField to
accommodate the suggested horizontal offset.

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.

Engr. Farhan Ahmed Umrani Page 154


Object Oriented Programming

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.

To set component resizeability behavior:


1. Control-click the two inserted JTextField components to select them in
the GUI Builder.
2. With both JTextFields selected, right-click either one of them and
choose Auto Resizing > Horizontal from the pop-up menu.
The JTextFields are set to resize horizontally at runtime. The
alignment guidelines and anchoring indicators are updated, providing
visual feedback of the component relationships.
To set components to be the same size:
1. Control-click all four of the JTextFields in the form to select them.
2. With the JTextFields selected, right-click any one of them and choose
Set Same Size > Same Width from the pop-up menu.
The JTextFields are all set to the same width and indicators are
added to the top edge of each, providing visual feedback of the
component relationships.
Now we need to add another JLabel describing the JComboBox that will enable users to select the format of the
information our ContactEditor application will display.

To align a JLabel to a component group:

Engr. Farhan Ahmed Umrani Page 155


Object Oriented Programming

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.

To align the baselines of components:


1. In the Palette window, select the Combo Box component from the
Swing Controls category.
2. Move the cursor immediately to the right of the JLabel we just added.
When the horizontal guideline appears indicating that the
JComboBox's baseline is aligned with the baseline of the text in the
JLabel and the spacing between the two components is suggested
with a vertical guideline, click to position the combo box.
The component snaps into a position aligned with the baseline of the
text in the JLabel to its left, as shown in the following illustration. The
GUI Builder displays status lines indicating the component's spacing
and anchoring relationships.

To resize the JComboBox:


1. Select the ComboBox in the GUI Builder.

Engr. Farhan Ahmed Umrani Page 156


Object Oriented Programming

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.

3. Press Ctrl-S to save the file.


Editing component models is beyond the scope of this tutorial, so for the time being we'll leave the JComboBox's
placeholder item list as it is.
top

Reviewing What We've Learned


We've got off to a good start building our ContactEditor GUI, but let's take a minute to recap what we've learned
while we add a few more of the components our interface requires.
Until now we've concentrated on adding components to our ContactEditor GUI using the IDE's alignment
guidelines to help us with positioning. It is important to understand, however, that another integral part of
component placement is anchoring. Though we haven't discussed it yet, you've already taken advantage of this
feature without realizing it. As mentioned previously, whenever you add a component to a form, the IDE suggests
the target look and feel's preferred positioning with guidelines. Once placed, new components are also anchored
to the nearest container edge or component to ensure that component relationships are maintained at runtime. In
this section, we'll concentrate on accomplishing the tasks in a more streamlined fashion while pointing out the
work the GUI builder is doing behind the scenes.

Adding, Aligning, and Anchoring


The GUI Builder enables you to lay out your forms quickly and easily by streamlining typical workflow gestures.
Whenever you add a component to a form, the GUI Builder automatically snaps them into the preferred positions
and sets the necessary chaining relationships so you can concentrate on designing your forms rather than
struggling with complicated implementation details.

To add, align, and edit the display text of a JLabel:


1. In the Palette window, select the Label component from the Swing
Controls category.
2. Move the cursor over the form immediately below the bottom JPanel's
E-mail title. When the guidelines appear indicating that it's positioned
in the top left corner of the JPanel with a small margin at the top and
left edges, click to place the JLabel.
3. Double-click the JLabel to select its display text. Then type E-mail
Address: and press Enter.
The JLabel snaps into the preferred position in the form, anchored to
the top and left edges of the enclosing JPanel. Just as before, a
corresponding node representing the component is added to the

Engr. Farhan Ahmed Umrani Page 157


Object Oriented Programming

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.

To add and resize a JList:


1. In the Palette window, select the List component from the Swing
Controls category.
2. Move the cursor immediately below the E-mail Address JLabel
we added earlier. When the guidelines appear indicating that the
JList's top and left edges are aligned with the preferred margins along
the JPanel's left edge and the JLabel above, click to position the JList.
3. Drag the JList's right resize handle toward the right of the enclosing
JPanel until the alignment guidelines appear indicating that it is the
same width as the JTextField above.
The JList snaps into the position designated by the alignment
guidelines and its corresponding node is displayed in the Inspector
window. Notice also that the form expands to accommodate the newly
added JList.

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.

Engr. Farhan Ahmed Umrani Page 158


Object Oriented Programming

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.

To add, align, and edit the display text of multiple buttons:


1. In the Palette window, select the Button component from the Swing
Controls category.
2. Move the JButton over the right edge of the E-mail
Address JTextField in the lower JPanel. When the guidelines
appear indicating that the JButton's baseline and right edge are
aligned with that of the JTextField, shift-click to place the first button
along the JFrame's right edge. The JTextField's width shrinks to
accommodate the JButton when you release the mouse button.

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.

Engr. Farhan Ahmed Umrani Page 159


Object Oriented Programming

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.

To set components to the same size:


1. Select all four JButtons by pressing the Control key while making your
selection.
2. Right-click one of them and choose Same Size > Same Width from
the pop-up menu.
The JButtons are set to the same size as the button with the longest
name.

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.

Engr. Farhan Ahmed Umrani Page 160


Object Oriented Programming

To indent JRadioButtons below a JLabel:


1. Add a JLabel named Mail Format to the form below the JList.
Make certain the label is left aligned with the JList above.
2. In the Palette window, select the Radio Button component from the
Swing category.
3. Move the cursor below the JLabel that we just added. When the
guidelines appear indicating that the JRadioButton's left edge is
aligned with that of the JLabel, move the JRadioButton slightly to the
right until secondary indentation guidelines appear. Shift-click to place
the first radio button.

4. Move the cursor to the right of the first JRadioButton. Shift-click to


place the second and third JRadioButtons, being careful to respect
the suggested component spacing. Make certain to release the Shift
key prior to positioning the last JRadioButton.
5. Set the display text for each JRadioButton. (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 HTML for the left
radio button, Plain Text for the second, and Custom for the
third.
Three JRadioButtons are added to the form and indented below
the Mail Format JLabel.

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.

Engr. Farhan Ahmed Umrani Page 161


Object Oriented Programming

To add JRadioButtons to a ButtonGroup:


1. In the Palette window, select the Button Group component from the Swing
Controls category.
2. Click anywhere in the GUI Builder design area to add the ButtonGroup
component to the form. Notice that the ButtonGroup does not appear in the
form itself, however, it is visible in the Navigator's Other Components area.
3. Select all three of the JRadioButtons in the form.
4. In the Properties window, choose buttonGroup1 from the buttonGroup
property combo box.
Three JRadioButtons are added to the button group.

5. Press Ctrl-S to save the file.

Making the Final Adjustments


We've managed to rough out our ContactEditor application's GUI, but there are still a few things remaining to do.
In this section, we'll take a look at a couple of other typical layout tasks that the GUI Builder streamlines.

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.

To add and edit the display text of buttons:


1. If the lower JPanel is extended to the bottom edge of the JFrame
form, drag the bottom edge of the JFrame down. This gives you space
between the edge of the JFrame and the edge of the JPanel for your
OK and Cancel buttons.
2. In the Palette window, select the Button component from the Swing
Controls category.
3. Move the cursor over the form below the E-mail JPanel. When the
guidelines appear indicating that the JButton's right edge is aligned
with the lower right corner of the JFrame, click to place the button.

Engr. Farhan Ahmed Umrani Page 162


Object Oriented Programming

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.

The JButton components appear in the form and their


corresponding nodes are displayed in the Navigator window.
The JButton components' code is also added to the form's source
file which is visible in the Editor's Source view. Each of the JButtons
are set to the same size as the button with the longest name.
7. Press Ctrl-S to save the file.
The last thing we need to do is delete the placeholder text in the various components. Note that while removing
placeholder text after roughing out a form can be a helpful technique in avoiding problems with component
alignments and anchoring relationships, most developers typically remove this text in the process of laying out
their forms. As you go through the form, select and delete the placeholder text for each of the JTextFields. We'll
leave the placeholder items in both the JComboBox and JList for a later tutorial.

Previewing Your GUI


Now that you have successfully built the ContactEditor GUI, you can try your interface to see the results. You can
preview your form as you work by clicking the Preview Form button ( ) in the GUI Builder's toolbar. The form
opens in its own window, allowing you to test it prior to building and running.

Engr. Farhan Ahmed Umrani Page 163


Object Oriented Programming

Deploying GUI Applications


In order for the interfaces you create with the GUI Builder to work outside of the IDE, the application must be
compiled against classes for the GroupLayout layout manager and also have those classes available at runtime.
These classes are included in Java SE 6, but not in Java SE 5. If you develop the application to run on Java SE
5, your application needs to use the Swing Layout Extensions library.
If you are running the IDE on JDK 5, the IDE automatically generates your application code to use the Swing
Layout Extensions library. When you deploy the application, you need to include the Swing Layout Extensions
library with the application. When you build the application (Build > Build Main Project), the IDE automatically
provides a copy of the library's JAR file in the application's dist/lib folder. The IDE also adds each of the
JAR files that are in the dist folder to the Class-Path element in the application JAR
file's manifest.mf file.
If you are running the IDE on JDK 6, the IDE generates your application code to use the GroupLayout classes
that are in Java SE 6. This means that you can deploy the application to run on systems with Java SE 6 installed
and you do not need to package your application with the Swing Layout Extensions library.
Note: If you create your application using JDK 6 but you need the application to also run on Java SE 5, you can
have the IDE generate its code to use the Swing Layout Extensions library instead of the classes in Java SE 6.
Open the ContactEditorUI class in the GUI Editor. In the Navigator, right-click the Form ContactEditorUI node
and choose Properties in the popup menu. In the Properties dialog box, change the value of the Layout
Generation Style property to Swing Layout Extensions Library.

Distributing and Running Standalone GUI Applications


To prepare your GUI application for distribution outside of the IDE:
 Zip the project's dist folder into a ZIP archive. (The dist folder might also contain a lib folder,
which you would also need to include.)
To run your application, right-click the project name and select Run in the context menu. In the Run Project
dialog select the main class name (my.contacteditor.ContactEditorUI if speaking about the project
you have just created) and click OK. Your application is up and running.
To run a standalone GUI application from the command line:
1. Navigate to the project's dist folder.

2. Type the following:


java -jar <jar_name>.jar
Note: If you encounter the following error:
Exception in thread "main" java.lang.NoClassDefFoundError:
org/jdesktop/layout/GroupLayout$Group

Engr. Farhan Ahmed Umrani Page 164


Object Oriented Programming
Ensure that the manifest.mf file references the currently installed version of the Swing Layout Extensions
Library.

Handling Images in a Java GUI Application


Contents

 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

NetBeans IDE Version 7.4 or 8.0

Java Development Kit (JDK) Version 6, 7 or 8

Introduction

Engr. Farhan Ahmed Umrani Page 165


Object Oriented Programming
Handling images in an application is a common problem for many beginning Java programmers. The standard
way to access images in a Java application is by using the getResource() method. This tutorial shows you
how to use the IDE's GUI Builder to generate the code to include images (and other resources) in your
application. In addition, you will learn how to customize the way the IDE generates image handling code.
The application that results from this tutorial will be a simple JFrame that contains one JLabel that displays a
single image.

Creating the Application


1. Choose File > New Project.
2. In the New Project wizard, select Java > Java Application and click Next.
3. For Project Name, type ImageDisplayApp.

4. Clear the Create Main Class checkbox.

5. Click Finish.

Creating the Application Form


In this section, you create the JFrame form and add a JLabel to the form.
To create the JFrame form:
1. In the Projects window, expand the ImageDisplayApp node.

2. Right-click the Source Packages node and choose New > JFrame Form.
3. For Class Name, type ImageDisplay.

4. For Package Name, type org.me.myimageapp.

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:

Engr. Farhan Ahmed Umrani Page 166


Object Oriented Programming

Adding a Package for the Image


When you use images or other resources in an application, typically you create a separate Java package for the
resources. On your local filesystem, a package corresponds with a folder.
To create a package for the image:
1. In the Projects window, right-click the org.me.myimageapp node and choose New > Java Package.

2. Click Finish.
In the Projects window, you should see a new package appear within the Source Packages folder.

Engr. Farhan Ahmed Umrani Page 167


Object Oriented Programming

Displaying the Image on the Label


In this application, the image will be embedded within a JLabel component.
To add the image to the label:
1. In the GUI Designer, select the label that you have added to your form.
2. In the Properties window, click the Properties category and scroll to the Icon property.
3. Click the ellipsis (...) button.
The icon property editor is displayed.

4. In the icon property dialog box, click Import to Project.


5. In the file chooser navigate to any image that is on your system that you want to use. Then click Next.
6. In the Select target folder page of the wizard, select the newpackage folder and click Finish.

Engr. Farhan Ahmed Umrani Page 168


Object Oriented Programming

7. Click OK to close the icon property dialog box.


After you click OK, the IDE does the following things:
 Copies the image to your project. Therefore, when you build and distribute the application, the image is
included in the distributable JAR file.

 Generates code in the ImageDisplay class to access the image.

 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.

 Drag the jLabel1 to the center of the form.

Engr. Farhan Ahmed Umrani Page 169


Object Oriented Programming

To view the generated code:


1. In the GUI Designer, click the Source button. (Choose View > Source Editor Toolbar from the main
menu if the Source button is hidden.)
2. Scroll down to the line that says Generated Code.
3. Click the plus sign (+) to the left of the Generated Code line to display the code that the GUI Designer
has generated.
The key line is the following:
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/org/me/myi
mageapp/newpackage/image.png"))); // NOI18N
Since you have used the property editor for jLabel1's Icon property, the IDE has generated
the setIcon method. The parameter of that method contains a call to the getResource() method on an
anonymous inner class of ImageIcon. Notice that the generated path for the image corresponds with its
location in the application's package structure.
Notes:
 If you use the External Image option in the icon property editor, the IDE will generate an absolute path
to the image instead of copying the image to your project. Therefore, the image would appear when you run the
application on your system, but it would probably not appear when running the application on another system.

 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.

Engr. Farhan Ahmed Umrani Page 170


Object Oriented Programming

Building and Running the Application


Now that you have generated the code for accessing and displaying the image, you can build and run the
application to ensure that the image is accessed.
First you need to set the project's main class. When you set the main class, the IDE knows which class to run
when you run the project. In addition, this ensures that the Main-Class element in the application's JAR file is
generated when you build the application.
To set the project's main class:
1. Right-click the ImageDisplayApp project's node and choose Properties.
2. In the Project Properties dialog box, select the Run category.
3. Click the Browse button that is next to the Main Class field. Then select
the org.me.myimageapp.ImageDisplay class.

4. Click the Select Main Class button.


5. Click OK to close the Project Properties dialog box.
To build the project:
 Choose Run > Clean & Build Project (project_name) from the main toolbar.
You can view the build products of the application in the Files window. The build folder contains the compiled
class. The dist folder contains a runnable JAR file that contains the compiled class and the image.

Engr. Farhan Ahmed Umrani Page 171


Object Oriented Programming

To run the project:


 Choose Run > Run Project (project_name) from the main toolbar.

Creating Custom Code


In many applications, the image that is displayed is not determined statically like it is in this example. For
example, the image to display might be determined by something that the user clicks.
If you need to be able to choose the image to display programmatically, you can write your own custom code to
access and display resources. The IDE prevents you from writing code directly in the Source view's "guarded
blocks" that contain code generated by the GUI Builder. However, you can insert code in the guarded blocks
through property editors that you can access through the Properties window. Using the property editors in this
manner ensures that your custom code is not lost when you make design changes in the GUI Builder.
For example, to write custom code for a JLabel's icon property:
1. Select the JLabel in the Design View or in the Navigator window.
2. In the Properties window, click the ellipsis (...) button that is next to the icon property.

3. From the dropdown list at the top of the dialog box, select the Custom Code option.

Engr. Farhan Ahmed Umrani Page 172


Object Oriented Programming

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.

Engr. Farhan Ahmed Umrani Page 173

You might also like