0% found this document useful (0 votes)
6 views86 pages

Cir 205 Notes

CIT 205: Object Oriented Programming II is a 3 credit hour course designed to enhance learners' skills in advanced Object Oriented Programming concepts necessary for modern enterprise applications. The course covers topics such as encapsulation, constructors, methods in Java, and generic programming, with a focus on practical implementation through various assessments. Students will engage in lectures, programming exercises, and discussions, utilizing core reading materials and resources to support their learning.

Uploaded by

amos74shadrack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views86 pages

Cir 205 Notes

CIT 205: Object Oriented Programming II is a 3 credit hour course designed to enhance learners' skills in advanced Object Oriented Programming concepts necessary for modern enterprise applications. The course covers topics such as encapsulation, constructors, methods in Java, and generic programming, with a focus on practical implementation through various assessments. Students will engage in lectures, programming exercises, and discussions, utilizing core reading materials and resources to support their learning.

Uploaded by

amos74shadrack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

CIT 205: OBJECT ORIENTED PROGRAMMING II 3 CREDIT HOURS

Prerequisites: CIR 104

Mr. Moses Wainaina


0707691430

Purpose of the Course


To equip the learners with advanced concepts and practical skills in Object Oriented
Programming that are necessary for creating stable high-level applications for the modern
enterprise
Expected Learning Outcomes
At the end of this course the learner shall be able to;
i. Demonstrate knowledge of OOP concepts and principles
ii. Implement Passing & Returning Objects
iii. Implement Polymorphism and inheritance
COURSE CONTENT
TOPIC 1: Hiding the Implementation, Initialization & Clean-up, Passing & Returning Objects,
and dynamic object creation.
TOPIC 2: Methods in Java
TOPIC 3: Advanced Object-Oriented Programming topics: Interfaces & Inner Classes,
Polymorphism and inheritance, handling exception and safety.
TOPIC 4: Generic programming: run-time type identification, templates and partial
specialization, auto pointers, traits and traits classes, design patterns, proxy classes, multiple
dispatch, operator overloading etc.
TOPIC 5: Collections of Objects: Arrays, Container, and Iterators. I/O System with streams.
Concurrency. Coding guidelines, programming guidelines.

1|Page Moses Wainaina - 0707691430


TOPIC 6: Applets in java
TOPIC 7: SQL database with netbean

CASE STUDIES: The Standard Library, the STL - its use and its internals.
Mode of Delivery
Lecturers, Class Programming Exercise, Group Exercises, Focused Group Discussions
Instructional Materials and Equipment
Whiteboard, Whiteboard Maker Pens, Projector, Computer and Appropriate Programming
Environment Software
Course Assessment
Continuous assessment tests (at least two CATs) 20%
Continuous assessment of the lab. Exercises 10%
End of semester exam; A written paper of 3 hours’ duration 70%
Total 100%
Staff performance
Evaluation forms completed by students
Core Reading Materials
1) Vaskaran, Sarcar (2020) Interactive Object-Oriented Programming in Java. Apress
2) Cay S. Horstmann and Gary Cornell (2013) Core Java, Volume II--Advanced
Features (9th Edition). Prentice Hall,
3) Balagurusamy, E (2013) Object Oriented Programming with C++: 6e. McGraw Hill
4) Nell Dale and Daniel T. Joyce (2011) Object-Oriented Data Structures Using Java.
Cathleen Sether
5) Khandare, S. S., (2011). Programming in Java S. Chand and Company Ltd
Recommended - Journals
1) Journal of Object-Oriented Programming - ACM Digital Library
2) The Journal of Object Technology
3) International Journal of Programming Languages and Applications

2|Page Moses Wainaina - 0707691430


TOPIC 1: HIDING THE IMPLEMENTATION, INITIALIZATION & CLEAN-UP,
PASSING & RETURNING OBJECTS

Hiding the implementation


Data hiding is an object-oriented programming technique of hiding internal object details i.e.
data members. Data hiding guarantees restricted data access to class members & maintain object
integrity
Encapsulation is one of the four fundamental OOP concepts. 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.
CLASSES IN JAVA
A class is an entity that determines how an object will behave and what the object will contain.
It is acting as a template that describes the data and behavior associated with instances of that
class.
When you instantiate a class means creating an object. The class contains set of variables and
methods.
The data associated with a class or object is stored in variables; the behavior associated with a
class or object is implemented with methods. A class is a blueprint from which individual objects
are created.
Synatx
class MyClass {
// field,

3|Page Moses Wainaina - 0707691430


//constructor, and
// method declarations
}

Example:
class Myclass{
public static void main(String[] args)
{
System.out.println(“Hello World!”); //Display the string.
}
}

The keyword class begins the class definition for a class named name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class definition
block. The “Hello World” application has no variables and has a single method named main.

In Java, the simplest form of a class definition is


class name {
...
}

CONSTRUCTOR
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
There are basically two rules defined for the constructor.

4|Page Moses Wainaina - 0707691430


1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
class Test {
Test () {
// constructor body
}
}

Types of java constructors


There are two types of constructors:
i. Default constructor (no-arg constructor)
ii. Parameterized constructor
Java Default Constructor
A constructor that has no parameter is known as default constructor.
If the constructor is not defined in a class, then compiler creates default constructor (with no
arguments) for the class.

Example
class Main {
int i;
// constructor with no parameter
Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
5|Page Moses Wainaina - 0707691430
System.out.println("Value of i: " + obj.i);
}
}

Output:
Constructor is called
Value of i: 5

- The program has created a constructor Main(). Here, the constructor does not accept any
parameters. Hence, it is known as a no-arg constructor.

Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to initialize
fields of the class with your own values, then use parameterized constructor.
Example
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}

6|Page Moses Wainaina - 0707691430


Output:
Java Programming Language
Python Programming Language
C Programming Language

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with different parameters so that every
constructor can perform a different task.
In other words, defining two or more constructors with the same name but with different
signatures is called constructor overloading in java. It is used to perform different tasks.
Java compiler differentiates these constructors based on the number of the parameter lists and
their types. Therefore, the signature of each constructor must be different.
The signature of a constructor consists of its name and sequence of parameter types.
If two constructors of a class have the same signature, it represents ambiguity. In this case, Java
compiler will generate an error message because Java compiler will unable to differentiate which
form to execute.
Hence, overloaded constructors must have different signatures. Java compiler decides which
constructor has to be called depending on the number of arguments passing with objects.
The simple form of constructor overloading in Java is shown in the below figure.

7|Page Moses Wainaina - 0707691430


Note: Overloading means more than one form. It refers to use of the same thing for a different
purpose

Use of Constructor overloading in Java


Overloaded constructors are very common to use in Java programming based on needs because
they provide many ways to create an object of a particular class. Constructor overloading
allows initializing objects with different types of data.
public class School
{
// Declare instance Variables.
String scName;
int estYear;
// Constructor overloading begins from here.
// Create default constructor and Initialize values. If you don't initialize values, default values
null and 0 will print as output provided by default constructor.
School()
{
scName = "RSVM";
estYear = 1975;
}

8|Page Moses Wainaina - 0707691430


// Create one parameter constructor and set the name of parameter different from name of the
variable because we are not using this reference.
School(String name)
{
scName = name;
}
// Create two parameters constructor and set the name of parameters different from name of
variables.
School(String name, int year)
{
scName = name;
estYear = year;
}
// Create an instance method to print output. You can also print output in const.
void display()
{
System.out.println(scName+ " " +estYear);
}
// Main method declaration.
public static void main(String[] args)
{
// Create the first object with object reference variable sc.
School sc = new School(); // Calling default constructor.

// Create second object with object reference variable sc1.


School sc1 = new School("RSVM"); // Calling one parameterized constructor because
declaration of an object is followed by one argument.

// Create the third object with object reference variable sc2.


School sc2 = new School("RSVM",1975); // Calling two parameterized constructor because
declaration of an object is followed by two arguments.

// Now, call methods using reference variables sc, sc1 and sc2 one by one to print output.
sc.display();
sc1.display();
sc2.display();
}
}

9|Page Moses Wainaina - 0707691430


Example 2
public class Student {
// Declaration of instance variables.
String name;
String schoolName;
int rollNo;
Student(String name, String sName)
{
this.name = name; // Here, 'this' reference is used.
schoolName = sName;
}
Student(String name, String sName, int rollNo)
{
this.name = name; // this reference.
schoolName = sName;
this.rollNo = rollNo;
}
void details()
{
System.out.println(name+ " " +schoolName+ " " +rollNo);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Create an object of class and pass the arguments to its constructors.
Student st = new Student("Riddhi", "DPS");
Student st2 = new Student("Siddhi", "RSVM", 05);
st.details();
st2.details();
}
}

Creating an Object
The class provides the blueprints for objects. The objects are the instances of the class. In
Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
 Declaration − A variable declaration with a variable name with an object type.

 Instantiation − The ‘new’ keyword is used to create the object.

10 | P a g e Moses Wainaina - 0707691430


 Initialization − The ‘new’ keyword is followed by a call to a constructor. This call
initializes the new object.
Creating a Class
To create a class, use the keyword class:
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}

Creating an Object
In Java, an object is created from a class. We have already created the class named Main, so now
we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}

Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
public class Main {
int x = 5;
public static void main(String[] args) {

11 | P a g e Moses Wainaina - 0707691430


Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}

sum of two numbers


package objectProgram;
public class Sum
{
// Declare instance variables.
int a;
int b;

// Declare a default constructor and initialize the value of variables.


// You can also initialize directly to the variables. This is another way to initialize the value of
variables.
Sum()
{
a = 50;
b = 20;
}

// Declare a method and write the logic to add the numbers.


void display()
{
int sum = a+b;
System.out.println("Sum of two numbers: " +sum );
}

public static void main(String[] args)


{
// Create an object of the class and call the method using reference variables to print output on
the console.
Sum sm = new Sum();
sm.display();
}
}

12 | P a g e Moses Wainaina - 0707691430


TOPIC 2 : METHODS IN JAVA
A method is a collection of statement that performs specific task. In Java, each method is a part
of a class and they define the behavior of that class.

When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.

Syntax

public static int methodName(int a, int b) {

// body

Here,

 public static − modifier

 int − return type

 methodName − name of the method

 a, b − formal parameters

 int a, int b − list of parameters

Method Declaration

The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.

13 | P a g e Moses Wainaina - 0707691430


Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.

max(int x, int y) Number of parameters is 2, Type of parameter is int.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.

o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.

o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.

o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.

14 | P a g e Moses Wainaina - 0707691430


Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.

Naming a Method

While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

NB: It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.

Method Calling

The method needs to be called for using its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:

 It completes all the statements in the method

 It reaches a return statement

 Throws an exception

Simple Program that call a method

public class Main


{
static void javaMethod()
{
System.out.println(" Java is easy to learn ");
}
public static void main(String[] args)
{
javaMethod();
}

15 | P a g e Moses Wainaina - 0707691430


}
Output:

Example 1: Sum of two numbers using method

// Java Program to Illustrate Methods

// Class 1
// Helper class
class Addition {
// Initially taking sum as 0
// as we have not started computation
int sum = 0;

// Method
// To add two numbers
public int addTwoInt(int a, int b)
{
// Adding two integer value
sum = a + b;
// Returning summation of two values
return sum;
}
}
// Class 2
// Helper class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of class 1 inside main() method
Addition add = new Addition();
// Calling method of above class
// to add two integer
// using instance created
int s = add.addTwoInt(1, 2);
// Printing the sum of two numbers
System.out.println("Sum of two integer values :"

16 | P a g e Moses Wainaina - 0707691430


+ s);
}
}

Parameters of a Method

Java methods have parameters (like ingredients) or data that are inputted or passed into the
method. The method uses these parameter values to do the necessary data manipulation and
processing. The method then usually returns the final value after all the necessary data
processing is successfully performed.

1. public int subtractNumbers(int m, int n) {


2. int p = 0;
3. p = m - n;
4. System.out.println(p);
5. return p;
6. }
In this example, m and n are parameters. The Java method subtract Numbers finds the
difference between m and n and saves the result in a new variable p. The values of the
parameters m and n are used to generate the new variable p that is printed out on the
computer screen.

Example 2
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Khan");
}

public static void main(String[] args) {


myMethod("Salman");
myMethod("Shahrukh");
myMethod("Aamir");
}
}
Output:

Methods with multiple parameters:


public class Main {
17 | P a g e Moses Wainaina - 0707691430
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}

public static void main(String[] args) {


myMethod("Sneha", 25);
myMethod("Sanjana", 21);
myMethod("Anju", 20);
}
}
OUTPUT:

Returning a Value
By using the parameters that are passed into the method, the method generates a new product
or result. The result returned by the method is also available for use by the Java program to
which this method belongs.
1. public int subtractNumbers(int m, int n) {
2. int p = 0;
3. p = m - n;
4. System.out.println(p);
5. return p;
6. }
In this example, the variable p is returned by the method. The return statement is a Java keyword
return followed by the variable name.

Example

public class Main


{
static int sum(int x)
{
return 5 + x;
}
public static void main(String[] args)
{

18 | P a g e Moses Wainaina - 0707691430


System.out.println(sum(19));
}
}
OUTPUT: 24

Methods that Do Not Return a Value

Some Java methods do not return a value; they process a set of tasks without a return value.
When a method does not return a value, it is indicated by the keyword void before the name of
the method.

1. public void subtractNumbers(int m, int n) {


2. int p;
3. p = m - n;
4. System.out.println(p);
5. }
This method does not return a value. Instead, it only prints the result of m-n on the screen. We
can tell that this method does not return a value because:

1. It has no return statement

2. The method name (subtractNumbers) is preceded by the keyword void

Different Types of Methods in Java

There are two types of methods in Java

1. Pre – Defined Methods/ Standard Library Methods/System defined Methods:

These are built – in methods in Java, which are instantly available to use in your program. The
Java class library will be present in java archive (i.e., *jar) file with Java Virtual Machine (JVM)
and Java Runtime Environment.

Examples:

Math functions – sqrt(), log(), min(), max(), avg(), sin(), cos(), tan(), round(),etc.

String function – length( ), substring ( ), replace ( ), charAt ( ), indexOf ( ) etc.

2. User – defined Methods:

These methods are created by the programmers for their requirement as per the programming
scenario / necessity.

19 | P a g e Moses Wainaina - 0707691430


Categories of user-defined methods

1) Method without returning any value


a) Calling Method by invoking Object
b) Calling Method without invoking Object

2) Method with returning a value.


a) Calling Method by invoking Object
b) Calling Method without invoking Object

Writing Methods (With returning a value)

a. Calling Method by invoking Object (calling the method with object)


package xyza;
public class JavaMethods {
//User defined Method
public int multiply(int a, int b, int c){
int result = a * b * c;
return result;
}

public static void main (String [] args){

//Create Object
JavaMethods abc = new JavaMethods();

//Call Method
int x = abc.multiply(10, 25, 35);
System.out.println(x);

System.out.println(abc.multiply(10, 25, 35));


}
}

b. Calling Method without invoking Object - creating a method (calling the


method without object)
package xyza;

public class JavaMethods {

20 | P a g e Moses Wainaina - 0707691430


//Create Method
public static int multiply(int a, int b, int c){
int result = a * b * c;
return result;
}

public static void main (String [] args){


//Call Method
int x = multiply(10, 25, 35);
System.out.println(x);

System.out.println(multiply(10, 25, 35));


}

Write method without returning any value

a) Creating a Method (call the method by invoking Object)

public class JavaMethods {


//Create Method
public void studentRank(int marks){
if (marks >= 600){
System.out.println(“Rank A”);
}
else if (marks >= 500){
System.out.println(“Rank B”);
}
else
System.out.println(“Rank C”);
}
public static void main (String [] args){
//Call method by invoking object
JavaMethods obj = new JavaMethods();
obj.studentRank(600);
}
}

b. creating a Method (call the method without Object)


public class JavaMethods {

21 | P a g e Moses Wainaina - 0707691430


//Create Method without returning any value (without object)
public static void studentRank(int marks){
if (marks >= 600){
System.out.println(“Rank A”);
}
else if (marks >= 500){
System.out.println(“Rank B”);
}
else{
System.out.println(“Rank C”);
}
}
public static void main (String [] args){
//Call method without object
studentRank(450);
}
}

More examples of java programs using methods

To check if number is odd or even using user defined methods

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
22 | P a g e Moses Wainaina - 0707691430
20. else
21. System.out.println(num+" is odd");
22. }
23. }

Output

Enter the number: 12

12 is even

TOPIC 3: Advanced Object Oriented Programming topics: Interfaces & Inner Classes,
Polymorphism and inheritance, memory management internals, handling exception and
safety.
Java Inner Classes (Nested Classes)
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable
and maintainable.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of Java inner classes
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-static nested
classes are also known as inner classes.

23 | P a g e Moses Wainaina - 0707691430


o Non-static nested class (inner class)
o Static nested class

1. Java Member Inner class


A non-static class that is created inside a class but outside a method is called member inner
class. It is also known as a regular inner class. It can be declared with access modifiers like
public, default, private, and protected.
Syntax:
class Outer{
//code
class Inner{
//code
}
}
Java Member Inner Class Example
In this example, we are creating a msg() method in the member inner class that is accessing the
private data member of the outer class. TestMemberOuter1.java
class TestMemberOuter1{
int data=30;
class Inner{
void msg()
{System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

Output:

24 | P a g e Moses Wainaina - 0707691430


Data is 30
2. Java static nested class
A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.
o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or
Java static nested class example with instance method
TestOuter1.java

class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of the Outer class because the nested class
is static and static properties, methods, or classes can be accessed without an object
Java static nested class example with a static method
If you have the static member inside the static nested class, you don't need to create an instance
of the static nested class.
TestOuter2.java
public class TestOuter2{
static int data=30;

25 | P a g e Moses Wainaina - 0707691430


static class Inner{
static void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter2.Inner.msg();//no need to create the instance of static nested class
}
}

Output:
data is 30]

Interface in Java
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
An interface is similar to a class in the following ways −
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
 An interface does not contain any constructors.

26 | P a g e Moses Wainaina - 0707691430


 All of the methods in an interface are abstract.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
We use the interface keyword to create an interface in Java. For example,
interface Language {
public void getType();

public void getVersion();


}

Here,
 Language is an interface.
 It includes abstract methods: getType() and getVersion().

Implementing an Interface
To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.
Example 1:
interface Polygon {
void getArea(int length, int breadth);
}

// implement the Polygon interface


class Rectangle implements Polygon {

// implementation of abstract method


public void getArea(int length, int breadth) {
System.out.println("The area of the rectangle is " + (length * breadth));
}
}

class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}

27 | P a g e Moses Wainaina - 0707691430


Output
The area of the rectangle is 30
In the above example, we have created an interface named Polygon. The interface contains an
abstract method getArea().
Here, the Rectangle class implements Polygon. And, provides the implementation of
the getArea() method.
Example 2
// create an interface
interface Language {
void getName(String name);
}

// class implements interface


class ProgrammingLanguage implements Language {

// implementation of abstract method


public void getName(String name) {
System.out.println("Programming Language: " + name);
}
}

class Main {
public static void main(String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage();
language.getName("Java");
}
}

Output
Programming Language: Java
In the above example, we have created an interface named Language. The interface includes an
abstract method getName().
Here, the ProgrammingLanguage class implements the interface and provides the
implementation for the method.

Advantages of Interface in Java

28 | P a g e Moses Wainaina - 0707691430


 Similar to abstract classes, interfaces help us to achieve abstraction in Java.

Here, we know getArea() calculates the area of polygons but the way area is calculated is
different for different polygons. Hence, the implementation of getArea() is independent
of one another.
 Interfaces provide specifications that a class (which implements it) must follow.

In our previous example, we have used getArea() as a specification inside the


interface Polygon. This is like setting a rule that we should be able to get the area of
every polygon.

Now any class that implements the Polygon interface must provide an implementation for
the getArea() method.
 Interfaces are also used to achieve multiple inheritance in Java. For example
interface Line {

}

interface Polygon {

}

class Rectangle implements Line, Polygon {



}
Here, the class Rectangle is implementing two different interfaces. This is how we
achieve multiple inheritance in Java.

Polymorphism and inheritance


Java Inheritance
Inheritance is one of the key features of OOP that allows us to create a new class from an
existing class.
The new class that is created is known as subclass (child or derived class) and the existing class
from where the child class is derived is known as superclass (parent or base class).
The extends keyword is used to perform inheritance in Java. For example,
class Animal {

29 | P a g e Moses Wainaina - 0707691430


// methods and fields
}

// use of extends keyword


// to perform inheritance
class Dog extends Animal {

// methods and fields of Animal


// methods and fields of Dog
}

In the above example, the Dog class is created by inheriting the methods and fields from
the Animal class.
Here, Dog is the subclass and Animal is the superclass.
Example 1:
class Animal {

// field and method of the parent class


String name;
public void eat() {
System.out.println("I can eat");
}
}

// inherit from Animal


class Dog extends Animal {

// new method in subclass


public void display() {
System.out.println("My name is " + name);
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// access field of superclass


labrador.name = "Rohu";

30 | P a g e Moses Wainaina - 0707691430


labrador.display();

// call method of superclass


// using object of subclass
labrador.eat();

}
}

Output
My name is Rohu
I can eat
In the above example, we have derived a subclass Dog from superclass Animal. Notice the
statements,
labrador.name = "Rohu";
labrador.eat();
Here, labrador is an object of Dog. However, name and eat() are the members of
the Animal class.
Since Dog inherits the field and method from Animal, we are able to access the field and method
using the object of the Dog.

31 | P a g e Moses Wainaina - 0707691430


Inheritance is-a relationship
In Java, inheritance is an is-a relationship. That is, we use inheritance only if there exists an is-a
relationship between two classes. For example,
 Car is a Vehicle
 Orange is a Fruit
 Surgeon is a Doctor
 Dog is an Animal
Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and so on.
Method Overriding in Java Inheritance
In Example 1, we see the object of the subclass can access the method of the superclass.
However, if the same method is present in both the superclass and subclass, what will
happen?
In this case, the method in the subclass overrides the method in the superclass. This concept is
known as method overriding in Java.
Example 2: Method overriding in Java Inheritance
class Animal {

32 | P a g e Moses Wainaina - 0707691430


// method in the superclass
public void eat() {
System.out.println("I can eat");
}
}

// Dog inherits Animal


class Dog extends Animal {

// overriding the eat() method


@Override
public void eat() {
System.out.println("I eat dog food");
}

// new method in subclass


public void bark() {
System.out.println("I can bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// call the eat() method


labrador.eat();
labrador.bark();
}
}

Output
I eat dog food
I can bark
In the above example, the eat() method is present in both the superclass Animal and the
subclass Dog.
Here, we have created an object labrador of Dog.

33 | P a g e Moses Wainaina - 0707691430


Now when we call eat() using the object labrador, the method inside Dog is called. This is
because the method inside the derived class overrides the method inside the base class.
This is called method overriding.
Super Keyword in Java Inheritance
Previously we saw that the same method in the subclass overrides the method in superclass.
In such a situation, the super keyword is used to call the method of the parent class from the
method of the child class.
Example 3: super Keyword in Inheritance
class Animal {

// method in the superclass


public void eat() {
System.out.println("I can eat");
}
}

// Dog inherits Animal


class Dog extends Animal {

// overriding the eat() method


@Override
public void eat() {

// call method of superclass


super.eat();
System.out.println("I eat dog food");
}

// new method in subclass


public void bark() {
System.out.println("I can bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

34 | P a g e Moses Wainaina - 0707691430


// call the eat() method
labrador.eat();
labrador.bark();
}
}

Output
I can eat
I eat dog food
I can bark
In the above example, the eat() method is present in both the base class Animal and the derived
class Dog. Notice the statement,
super.eat();
Here, the super keyword is used to call the eat() method present in the superclass.
We can also use the super keyword to call the constructor of the superclass from the constructor
of the subclass.
Protected Members in Inheritance
In Java, if a class includes protected fields and methods, then these fields and methods are
accessible from the subclass of the class.
Example 4: protected Members in Inheritance
class Animal {
protected String name;

protected void display() {


System.out.println("I am an animal.");
}
}

class Dog extends Animal {

public void getInfo() {


System.out.println("My name is " + name);
}
}

class Main {
public static void main(String[] args) {

35 | P a g e Moses Wainaina - 0707691430


// create an object of the subclass
Dog labrador = new Dog();

// access protected field and method


// using the object of subclass
labrador.name = "Rocky";
labrador.display();

labrador.getInfo();
}
}

Output
I am an animal.
My name is Rocky
In the above example, we have created a class named Animal. The class includes a protected
field: name and a method: display().
We have inherited the Dog class inherits Animal. Notice the statement,
labrador.name = "Rocky";
labrador.display();
Here, we are able to access the protected field and method of the superclass using
the labrador object of the subclass.
Why use inheritance?
 The most important use of inheritance in Java is code reusability. The code that is present
in the parent class can be directly used by the child class.
 Method overriding is also known as runtime polymorphism. Hence, we can achieve
Polymorphism in Java with the help of inheritance.

Types of inheritance
There are five types of inheritance.
1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For example

36 | P a g e Moses Wainaina - 0707691430


2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a superclass and then the same subclass acts as
a superclass for another class. For example,

3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For example,

4. Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple super classes. For example,

37 | P a g e Moses Wainaina - 0707691430


5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. For example,

Java Polymorphism
Polymorphism is an important concept of object-oriented programming. It simply means more
than one form.
That is, the same entity (method or operator or object) can perform different operations in
different scenarios.
Example
class Polygon {

// method to render a shape


public void render() {
System.out.println("Rendering Polygon...");
}
}

class Square extends Polygon {

// renders Square
public void render() {
System.out.println("Rendering Square...");

38 | P a g e Moses Wainaina - 0707691430


}
}

class Circle extends Polygon {

// renders circle
public void render() {
System.out.println("Rendering Circle...");
}
}

class Main {
public static void main(String[] args) {

// create an object of Square


Square s1 = new Square();
s1.render();

// create an object of Circle


Circle c1 = new Circle();
c1.render();
}
}

Output
Rendering Square...
Rendering Circle...
In the above example, we have created a superclass: Polygon and two
subclasses: Square and Circle. Notice the use of the render() method.
The main purpose of the render() method is to render the shape. However, the process of
rendering a square is different than the process of rendering a circle.
Hence, the render() method behaves differently in different classes. Or, we can say render() is
polymorphic.

Why Polymorphism?
Polymorphism allows us to create consistent code. In the previous example, we can also create
different methods: renderSquare() and renderCircle() to render Square and Circle, respectively.

39 | P a g e Moses Wainaina - 0707691430


This will work perfectly. However, for every shape, we need to create different methods. It will
make our code inconsistent.
To solve this, polymorphism in Java allows us to create a single method render() that will behave
differently for different shapes.
We can achieve polymorphism in Java using the following ways:
1. Method Overriding
2. Method Overloading

Java Method Overriding


During inheritance in Java, if the same method is present in both the superclass and the subclass.
Then, the method in the subclass overrides the same method in the superclass. This is called
method overriding.
In this case, the same method will perform one operation in the superclass and another operation
in the subclass. For example,
Example 1: Polymorphism using method overriding
class Language {
public void displayInfo() {
System.out.println("Common English Language");
}
}

class Java extends Language {


@Override
public void displayInfo() {
System.out.println("Java Programming Language");
}
}

class Main {
public static void main(String[] args) {

// create an object of Java class


Java j1 = new Java();
j1.displayInfo();

// create an object of Language class


Language l1 = new Language();
l1.displayInfo();

40 | P a g e Moses Wainaina - 0707691430


}
}

Output:
Java Programming Language
Common English Language
In the above example, we have created a superclass named Language and a subclass named Java.
Here, the method displayInfo() is present in both Language and Java.
The use of displayInfo() is to print the information. However, it is printing different information
in Language and Java.
Based on the object used to call the method, the corresponding information is printed.

Java Method Overloading


In a Java class, we can create methods with the same name if they differ in parameters. For
example,
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

This is known as method overloading in Java. Here, the same method will perform different
operations based on the parameter.
Example 3: Polymorphism using method overloading
class Pattern {

41 | P a g e Moses Wainaina - 0707691430


// method without parameter
public void display() {
for (int i =1; i <=10; i++) {
System.out.print("*");
}
}

// method with single parameter


public void display(char symbol) {
for (int i =1; i <=10; i++) {
System.out.print(symbol);
}
}
}

class Main {
public static void main(String[] args) {
Pattern d1 = new Pattern();

// call method without any argument


d1.display();
System.out.println("\n");

// call method with a single argument


d1.display('#');
}
}

Output:
**********
##########
In the above example, we have created a class named Pattern. The class contains a method
named display() that is overloaded.
// method with no arguments
display() {...}

42 | P a g e Moses Wainaina - 0707691430


// method with a single char type argument
display(char symbol) {...}
Here, the main function of display() is to print the pattern. However, based on the arguments
passed, the method is performing different operations:
 prints a pattern of *, if no argument is passed or
 prints pattern of the parameter, if a single char type argument is passed.

EXCEPTION HANDLING:
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.
What is exception?
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user
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.
Difference between error and exception
Errors indicate that something severe enough has gone wrong, the application should crash
rather than try to handle the error.
Exceptions are events that occur in the code. A programmer can handle such conditions and take
necessary corrective actions. Few examples:
Null Pointer Exception – When you try to use a reference that points to null.
Arithmetic Exception – When bad data is provided by user, for example, when you try to divide
a number by zero this exception occurs because dividing a number by zero is undefined.
Array Index Out Of Bounds Exception – When you try to access the elements of an array out of
its bounds, for example array size is 5 (which mean it has five elements) and you are trying to
access the 10th element.

Types of exceptions

43 | P a g e Moses Wainaina - 0707691430


There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, you will get compilation error.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked
at compile-time so compiler does not check whether the programmer has handled them or not but
it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For
example,
Multithreading
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.
Life cycle of a Thread (Thread States)
Threads exist in several states. Following are those states:
 New – When we create an instance of Thread class, a thread is in a new state.
 Runnable – The Java thread is in running state.
 Suspended – A running thread can be suspended, which temporarily suspends its
activity. A suspended thread can then be resumed, allowing it to pick up where it left off.
 Blocked – A java thread can be blocked when waiting for a resource.

44 | P a g e Moses Wainaina - 0707691430


 Terminated – A thread can be terminated, which halts its execution immediately at any
given time. Once a thread is terminated, it cannot be resumed.

Advantages of thread
 Reduces development time.
 Reduces maintenance costs.
 Improves the performance of complex applications.
 Useful for improving the responsiveness of the user interfaces.
 Used in server applications to improve high throughput and resource utilization.
 Parallelize tasks.
 If a thread cannot use all the computing resources of the CPU (because instructions
depend on each other’s result), running another thread can avoid leaving these idle.
 Take advantage of multiprocessor systems
Disadvantages of thread
 Multiple threads can interfere with each other when sharing hardware resources such as
caches or translation lookaside buffers (TLBs).

45 | P a g e Moses Wainaina - 0707691430


 Execution times of a single thread can be degraded, even when only one thread is
executing. This is due to slower frequencies and/or additional pipeline stages that are
necessary to accommodate thread-switching hardware.
 Hardware support for multithreading is more visible to software, thus requiring more
changes to both application programs and operating systems than multiprocessing.
Uses of Thread
 Java applications are naturally threaded. The runtime environment begins the execution
of the program with the main() method in one thread. Garbage collection takes place in
another thread. Screen updating occurs in a third thread. There may be other threads
running as well, mostly related to the behavior of the virtual machine. All of this happens
invisibly to the programmer. Sometimes you’re only concerned with what happens in the
primary thread which includes the main() method of a program. If this is the case, you
may not need to worry about threading at all.
 The main purpose of multithreading is to provide simultaneous execution of two or more
parts of a program to utilize the CPU time as much as possible. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is
called a thread. Each thread has a separate path of its execution. This way a single
program can perform two or more tasks simultaneously.
 Threads are lightweight processes; they share the same address space. In a Multithreaded
environment, programs make maximum use of CPU so that the idle time can be kept to a
minimum.
 To perform asynchronous or background processing.

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. The extending
class must override run() method which is the entry point of new thread.
Java Thread Example by extending Thread class
class Multi extends Thread{

46 | P a g e Moses Wainaina - 0707691430


public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.run();
}}

Output: thread is running...

Implementing the Runnable Interface


The easiest way to create a thread is to create a class that implements the runnable interface.
After implementing runnable interface , the class needs to implement the run() method, which is
public void run()
 run() method introduces a concurrent thread into your program. This thread will end
when run() returns.
 You must specify the code for your thread inside run() method.
 run() method can call other methods, can use other classes and declare variables just like
any other normal method.
Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])

47 | P a g e Moses Wainaina - 0707691430


{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.run();
}}

Output: thread is running...

TOPIC 3: Generic programming design patterns, proxy classes, operator overloading etc.
Design Patterns in Java
Design patterns represent the best practices used by experienced object-oriented software
developers. Design patterns are solutions to general problems that software developers faced
during software development. These solutions were obtained by trial and error by numerous
software developers over quite a substantial period of time.
It’s not mandatory to always implement design patterns in your project. Design patterns are not
meant for project development. Design patterns are meant for common problem-solving.
Whenever there is a need, you have to implement a suitable pattern to avoid such problems in the
future. To find out which pattern to use, you just have to try to understand the design patterns
and their purposes. Only by doing that, you will be able to pick the right one
Example:
In many real-world situations, we want to create only one instance of a class. For example, there
can be only one active president of a country at any given time. This pattern is called a Singleton
pattern. Other software examples could be a single DB connection shared by multiple objects as
creating a separate DB connection for every object is costly. Similarly, there can be a single
configuration manager or error manager in an application that handles all problems instead of
creating multiple managers.
Some of the benefits of using design patterns are:
1. Design Patterns are already defined and provides industry standard approach to solve a
recurring problem, so it saves time if we sensibly use the design pattern. There are many
java design patterns that we can use in our java based projects.
2. Using design patterns promotes reusability that leads to more robust and highly
maintainable code. It helps in reducing total cost of ownership (TCO) of the software
product.

48 | P a g e Moses Wainaina - 0707691430


3. Since design patterns are already defined, it makes our code easy to understand and
debug. It leads to faster development and new members of team understand it easily.
4. They capture the software engineering experiences.
5. They provide transparency to the design of an application.
6. They are well-proved and testified solutions since they have been built upon the
knowledge and experience of expert software developers.
7. Design patterns don’t guarantee an absolute solution to a problem. They provide clarity to
the system architecture and the possibility of building a better system.

When should we use the design patterns?


We must use the design patterns during the analysis and requirement phase of SDLC
(Software Development Life Cycle).
Design patterns ease the analysis and requirement phase of SDLC by providing information
based on prior hands-on experiences
Types of Design Patterns
There are mainly three types of design patterns:
1. Creational
These design patterns are all about class instantiation or object creation. These patterns
can be further categorized into Class-creational patterns and object-creational patterns.
While class-creation patterns use inheritance effectively in the instantiation process,
object-creation patterns use delegation effectively to get the job done.
Creational design patterns are the Factory Method, Abstract Factory, Builder, Singleton, Object
Pool, and Prototype.
Use case of creational design pattern-
1) Suppose a developer wants to create a simple DBConnection class to connect to a database
and wants to access the database at multiple locations from code, generally what the developer
will do is create an instance of DBConnection class and use it for doing database operations
wherever required. This results in creating multiple connections from the database as each
instance of DBConnection class will have a separate connection to the database. In order to deal
with it, we create DBConnection class as a singleton class, so that only one instance of
DBConnection is created and a single connection is established. Because we can manage DB
Connection via one instance, we can control load balance, unnecessary connections, etc.
2) Suppose you want to create multiple instances of a similar kind and want to achieve
loose coupling then you can go for Factory pattern. A class implementing factory design pattern
works as a bridge between multiple classes. Consider an example of using multiple database
49 | P a g e Moses Wainaina - 0707691430
servers like SQL Server and Oracle. If you are developing an application using SQL Server
database as back end, but in the future need to change the database to the oracle, you will need to
modify all your code, so as factory design patterns maintain loose coupling and easy
implementation, we should go for the factory design pattern in order to achieve loose coupling
and the creation of a similar kind of object.
2. Structural
These design patterns are about organizing different classes and objects to form larger
structures and provide new functionality.
Structural design patterns are Adapter, Bridge, Composite, Decorator, Facade, Flyweight,
Private Class Data, and Proxy.
Use Case Of Structural Design Pattern-
1) When 2 interfaces are not compatible with each other and want to establish a relationship
between them through an adapter it’s called an adapter design pattern. The adapter pattern
converts the interface of a class into another interface or class that the client expects, i.e adapter
lets classes work together that could not otherwise because of incompatibility. so in these types
of incompatible scenarios, we can go for the adapter pattern.
3. Behavioral
Behavioral patterns are about identifying common communication patterns between
objects and realizing these patterns.
Behavioral patterns are Chain of responsibility, Command, Interpreter, Iterator, Mediator,
Memento, Null Object, Observer, State, Strategy, Template method, Visitor
Use Case of Behavioral Design Pattern-
1) The template pattern defines the skeleton of an algorithm in an operation deferring some steps
to sub-classes. The template method lets subclasses redefine certain steps of an algorithm
without changing the algorithm structure. For example, in your project, you want the behavior of
the module to be able to extend, such that we can make the module behave in new and different
ways as the requirements of the application change, or to meet the needs of new applications.
However, no one is allowed to make source code changes to it, i.e you can add but can’t modify
the structure in those scenarios a developer can approach template design pattern.

Java Singleton Class


In Java, Singleton is a design pattern that ensures that a class can only have one object.
To create a singleton class, a class must implement the following properties:
 Create a private constructor of the class to restrict object creation outside of the class.
 Create a private attribute of the class type that refers to the single object.

50 | P a g e Moses Wainaina - 0707691430


 Create a public static method that allows us to create and access the object we created.
Inside the method, we will create a condition that restricts us from creating more than one
object.

Example: Java Singleton Class Syntax


class SingletonExample {

// private field that refers to the object


private static SingletonExample singleObject;

private SingletonExample() {
// constructor of the SingletonExample class
}

public static SingletonExample getInstance() {


// write code that allows us to create only one object
// access the object as per our need
}
}

In the above example,


 Private static SingletonExample single Object - a reference to the object of the class.
 Private SingletonExample() - a private constructor that restricts creating objects outside
of the class.
 Public static SingletonExample getInstance() - this method returns the reference to the
only object of the class. Since the method static, it can be accessed using the class name.
Use of Singleton in Java
Singletons can be used while working with databases. They can be used to create a connection
pool to access the database while reusing the same connection for all the clients. For example,
class Database {

51 | P a g e Moses Wainaina - 0707691430


private static Database dbObject;
private Database() {
}
public static Database getInstance() {
// create object if it's not already created
if(dbObject == null) {
dbObject = new Database();
}
// returns the singleton object
return dbObject;
}
public void getConnection() {
System.out.println("You are now connected to the database.");
}
}
class Main {
public static void main(String[] args) {
Database db1;

// refers to the only object of Database


db1= Database.getInstance();
db1.getConnection();
}
}
When we run the program, the output will be:
You are now connected to the database.
In our above example,
 We have created a singleton class Database.
 The dbObject is a class type field. This will refer to the object of the class Database.
 The private constructor Database() prevents object creation outside of the class.
 The static class type method getInstance() returns the instance of the class to the outside
world.
 In the Main class, we have class type variable db1. We are
calling getInstance() using db1 to get the only object of the Database.
 The method getConnection() can only be accessed using the object of the Database.
 Since the Database can have only one object, all the clients can access the database
through a single connection.

52 | P a g e Moses Wainaina - 0707691430


Singleton is a design pattern rather than a feature specific to Java. A design pattern is like our
code library that includes various coding techniques shared by programmers around the world.

Proxy classes
Proxy is a design pattern. In Proxy pattern, a proxy object represents a placeholder or surrogate
which provides an interface to outer world to access the functionality of original object. A proxy
object is simply means an object representing another object. Proxies are also known as handles,
surrogates, and wrappers. This type of design pattern comes under structural design pattern.
We create and use proxy objects when we want to add or modify some functionality of an
already existing class. The proxy object is used instead of the original one. Usually, the proxy
objects have the same methods as the original one and in Java proxy classes usually extend the
original class.
Example
The Proxy provides a surrogate or place holder to provide access to an object. A check or bank
draft is a proxy for funds in an account. A check can be used in place of cash for making
purchases and ultimately controls access to cash in the issuer's account.

Advantages of Proxy Pattern


 In proxy pattern, we provide interface of functionality supported by original object to
outer world to hide the complexity of the original object.
 Proxy provides an additional layer of protection to the original object from the outside
world.

53 | P a g e Moses Wainaina - 0707691430


 A local proxy code running on the client machine can enforce the constraints required by
to access the server. It can perform some operations locally before making a remote call
to server.
 Proxy pattern increases the performance of the application by avoids creation or
duplication of objects which might be complex and memory intensive.

Types of proxies
Remote proxy:
They are responsible for representing the object located remotely. Talking to the real object
might involve marshaling and unmarshalling of data and talking to the remote object. All that
logic is encapsulated in these proxies and the client application need not worry about them.
Virtual proxy:
These proxies will provide some default and instant results if the real object is supposed to take
some time to produce results. These proxies initiate the operation on real objects and provide a
default result to the application. Once the real object is done, these proxies push the actual data
to the client where it has provided dummy data earlier.
Protection proxy:
If an application does not have access to some resource then such proxies will talk to the objects
in applications that have access to that resource and then get the result back.

Types of proxy
There are four situations in which the Proxy pattern is used.
 Virtual proxy
suppose, you want to access a huge file from a database. Since, initialization of a
database client is expensive operation, we will use proxy pattern to instantiate an
instance of database client on first database request by client. After the first request,
proxy will reuse the database client for any future requests by client instead of creating a
new instance of database client every time. This will reduce the duplication of object,
reduce latency to access data from database and save memory.

54 | P a g e Moses Wainaina - 0707691430


 Remote proxy
A remote proxy of a remote resource (like a web services) provides a local interface of
the remote resource at different address location. A client can use the interface provided
by remote proxy or a remote resources to access the functionalities of a remove resource.
Talking to the remote resource might involve serialization and deserialization of data, all
such logic can be encapsulated in remote proxies and the client application need not
worry about their implementation. Examples of remote proxies include a proxy of REST
service or aws S3.
 Smart Proxy
A smart proxy can provide some additional functionality to access or optimize the
interaction between client and resource like splitting a large request to access 100
images into 5 requests of 20 images each. Other uses of smart proxies include providing
additional security, to provide failure handling in case or any problem while accessing
resource etc.
 Protection proxy
a protection proxy is used to enforce access control to a resource. It acts as an
authorization layer to verify that whether client has access necessary access the
appropriate resource or not. If client have appropriate access then it will forward the
client's request to the resource else block the unauthorized client request from accessing
the resource.

Operator overloading
Operator overloading is a technique by which operators used in a programming language are
implemented in user-defined types with customized logic that is based on the types of arguments
passed.
Operator overloading facilitates the specification of user-defined implementation for operations
wherein one or both operands are of user-defined class or structure type. This helps user-defined
types to behave much like the fundamental primitive data types. Operator overloading is helpful
in cases where the operators used for certain types provide semantics related to the domain
context and syntactic support as found in the programming language. It is used for syntactical
convenience, readability and maintainability.
For example, using a plus operator + for adding two numbers and concatenating two strings is
the simplest case of operator overloading.
However, Java does not support operator overloading except for one case, string concatenation
using the plus operator.
Here is the complete example.
import java.util.Scanner;
public class OperatorOverloading {

55 | P a g e Moses Wainaina - 0707691430


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
//Input the first string
System.out.println("Enter a string");
String s1 = sc.next();
//Input the second string
System.out.println("Enter another string: ");
String s2 = sc.next();
//Plus operator concatenates the two Strings
System.out.println(s1+' '+s2);
//Input the first integer
System.out.println("Enter a number");
int x = sc.nextInt();
//Input the second integer
System.out.println("Enter another number");
int y = sc.nextInt();
//Plus operator adds the two numbers
System.out.println("sum is:" +(x+y));
}
}

Output:
Enter a string
Hello
Enter another string:
World
Hello World
Enter a number
3
Enter another number
4
7
In this example, the plus operator adds the two integers and concatenates the two strings. It is the
only operator overloading that Java supports.
Other than this, Java does not support user-defined operator overloading. The only part of Java
close to operator overloading is the handling of + for concatenating strings.

56 | P a g e Moses Wainaina - 0707691430


It results in the compile-time concatenation of constants or run-time concatenation. However, in
Java, we cannot define our operators, which act like this.
Although we can concatenate strings in Java using the plus operator, Java has an in-
built concat() method that eliminates the need to perform operator overloading.
The concat() method appends another string at the end of a given string.
We should specify the strings to get the combined string in the order we desire.
Syntax:

String resultant = String1. concat(String2)

It will add the second string at the end of the first string. The example below uses
the concat() method to put together two strings.

import java.util.Scanner;

public class OperatorOverloading {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter a string:");

String s1 = sc.next();

System.out.println("Enter another string:");

String s2 = sc.next();

//Concatenate the two strings using concat() method

String res = s1.concat(s2);

System.out.println(res);

Output:
Enter a string:

57 | P a g e Moses Wainaina - 0707691430


Hello
Enter another string:
World
HelloWorld
Note that here, we are not using the plus operator for string concatenation, and we can still
combine the two strings with the help of the concat() method.

Reasons Why Java Doesn’t Support Operator Overloading


We can redefine most of the built-in operators in C++ but not in Java. It is due to the following
reasons.
 Operator overloading increases code complexity. If we overload an operator in Java, the
Java Virtual Machine (JVM) in Java needs to put an extra effort to find out the actual
functionality of the operator used in any particular statement. It makes the processing
quite complex.
 Operator overloading introduces errors in the program. Operator overloading creates
confusion amongst programmers. Also, working with languages that support operator
overloading has chances of error compared to other languages. Java has method
overloading. Method Overloading serves the functionality of operator overloading and
eliminates the scope for errors.
 Java supports method overloading. Method overloading is the concept of a class having
more than a single method with the same name but different parameters. The
identification of the method that is to be used is easier here. It depends on the number of
arguments or the data type of the arguments.

58 | P a g e Moses Wainaina - 0707691430


TOPIC 4: Collections in Java
The Collection in Java is a framework that provides architecture to store and manipulate the
group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces.
A Collection represents a single unit of objects, i.e., a group.
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for the Collection framework.

59 | P a g e Moses Wainaina - 0707691430


Iterator interface

Iterator interface provides the facility of iterating the elements in a forward direction only.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in
which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :

1. List <
data-type> list1= new ArrayList<>;

60 | P a g e Moses Wainaina - 0707691430


2. List <
data-type> list2 = new LinkedList();
3. List <
data-type> list3 = new Vector();
4. List <
data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
1. ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the
following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> list=new ArrayList<>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

61 | P a g e Moses Wainaina - 0707691430


Output
Ravi
Vijay
Ravi
Ajay

2. LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
LinkedList<String> al=new LinkedList<>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi

62 | P a g e Moses Wainaina - 0707691430


Vijay
Ravi
Ajay

3. Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, it is
synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
Vector<String> v=new Vector<>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
63 | P a g e Moses Wainaina - 0707691430
Ashish
Garima
4. Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack.
The stack contains all of the methods of Vector class and also provides its methods like boolean
push(), boolean peek(), boolean push(object o), which defines its properties.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
Stack<String> stack = new Stack<>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit

64 | P a g e Moses Wainaina - 0707691430


Ashish

Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is
used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:
1. Queue<String> q1 = new PriorityQueue();
2. Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given below.

ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
Deque<String> deque = new ArrayDeque<>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}

65 | P a g e Moses Wainaina - 0707691430


}
}
Output:
Gautam
Karan
Ajay

LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null elements.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
LinkedHashSet<String> set=new LinkedHashSet<>();
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi

66 | P a g e Moses Wainaina - 0707691430


Vijay
Ajay
Java ArrayList
Java ArrayList class uses a dynamic array
For storing the elements. It is like an array, but there is no size limit. We can add or remove
elements anytime. So, it is much more flexible than the traditional array. It is found in
the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so
we can use all the methods of the List interface here. The ArrayList maintains the insertion order
internally.
It inherits the AbstractList class and implements List interface
o In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot
of shifting needs to occur if any element is removed from the array list.
o We cannot create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases. For example:
1. ArrayList<int> al = ArrayList<int>(); // does not work
2. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
Java ArrayList Example
FileName: ArrayListExample1.java
package testjavacollection1;
import java.util.*;
public class ArrayListExample1{
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> list=new ArrayList<>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object

67 | P a g e Moses Wainaina - 0707691430


System.out.println(list);
}
}
Output:
[Mango, Apple, Banana, Grapes]
Iterating ArrayList using Iterator
Let's see an example to traverse ArrayList elements using the Iterator interface.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> list=new ArrayList<>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}

Output:
Mango
Apple

68 | P a g e Moses Wainaina - 0707691430


Banana
Grapes
Java Iterator
Java Iterator
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.
It is called an "iterator" because "iterating" is the technical term for looping.
To use an Iterator, you must import it from the java.util package.
Getting an Iterator
The iterator() method can be used to get an Iterator for any collection:
package testjavacollection1;
import java.util.ArrayList;
import java.util.Iterator;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
Integer i = it.next();
if(i < 10) {
it.remove();
}
}
System.out.println(numbers);
}
69 | P a g e Moses Wainaina - 0707691430
}
Output
[12, 23]

Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating systems) subroutine for
creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have different
look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this
is the platforms have different view for their native components and AWT directly calls the
native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window

70 | P a g e Moses Wainaina - 0707691430


The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window. We need to create an instance of Window class to create
this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container while
developing an AWT application.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
package awtexample1;
import java.awt.*;
public class AWTExample1 extends Frame{
// initializing using constructor
AWTExample1() {
// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height

71 | P a g e Moses Wainaina - 0707691430


setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String[] args) {
// TODO code application logic here
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
creating a TextField, Label and Button component on the Frame.

72 | P a g e Moses Wainaina - 0707691430


package wen;
import java.awt.*;
public class WEN {
WEN() {
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// setting position of above components in the frame
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
// adding components into frame
f.add(b);
f.add(l);
f.add(t);
// frame size 300 width and 300 height
f.setSize(400,300);
// setting the title of frame
f.setTitle("Employee info");
// no layout
f.setLayout(null);

// setting visibility of frame

73 | P a g e Moses Wainaina - 0707691430


f.setVisible(true);
}
// main method
public static void main(String[] args) {
// TODO code application logic here
// creating instance of Frame class
WEN awt_obj = new WEN();
}
}

APPLETS IN JAVA
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
74 | P a g e Moses Wainaina - 0707691430
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.

Life Cycle of an Applet


Four methods in the Applet class gives you the framework on which you build any serious applet

 init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
 start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
 stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
 paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet


Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {

75 | P a g e Moses Wainaina - 0707691430


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}

How to create an applet


Create a new project and give a name. don’t select the main class

Right click on the source package under your class, create new java applet under others

76 | P a g e Moses Wainaina - 0707691430


Give your applet a name and click finish

77 | P a g e Moses Wainaina - 0707691430


Applets do not have public static void statement. Instead they have Public void paint (Graphic g)
that enable the statement to displayed on window

Write the following code (Line 1 , line 14,15 and 16) Write click on your code and run your
program
import java.applet.Applet;
1. import java.awt.*;
2. /**
3. *
4. @author HP i7

78 | P a g e Moses Wainaina - 0707691430


5. */
6. public class NewApplet extends Applet {

7. /**
8. Initialization method that will be called after the applet is loaded into
9. the browser.
10. */
11. public void init() {
12. // TODO start asynchronous download of heavy resources
13. }
14. public void paint (Graphics g) {
15. g.drawString ("Hello World", 25, 50);
16. }
17. // TODO overwrite start(), stop() and destroy() methods
18. }
Run your program after writing your applet

Application Conversion to Applets

79 | P a g e Moses Wainaina - 0707691430


It is easy to convert a graphical Java application (that is, an application that uses the AWT and
that you can start with the Java program launcher) into an applet that you can embed in a web
page.
Following are the specific steps for converting an application to an applet.
 Make an HTML page with the appropriate tag to load the applet code.
 Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet
cannot be loaded.
 Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
 Move any initialization code from the frame window constructor to the init method of the
applet. You don't need to explicitly construct the applet object. The browser instantiates it
for you and calls the init method.
 Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
 Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates
when the browser exits.
 If the application calls setTitle, eliminate the call to the method. Applets cannot have title
bars. (You can, of course, title the web page itself, using the HTML title tag.)
 Don't call setVisible(true). The applet is displayed automatically.

To create login form using applets


Create a new project

80 | P a g e Moses Wainaina - 0707691430


Create new Jframe form under package source of your class

Give your form a name

Add labels, textfield and buttons to your form

81 | P a g e Moses Wainaina - 0707691430


You can edit the variable names of the text box
Under password add password filed

Right click on button then events –button- and action performed to write the code

82 | P a g e Moses Wainaina - 0707691430


This is where you start writing your program

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:


String Username=user.getText();
String Password =pass.getText();

83 | P a g e Moses Wainaina - 0707691430


if (Username.contains("cs") && Password.contains("cs"))
{
user.setText("");
pass.setText("");

newf obj = new newf();


obj.setVisible(true);
}
else{
System.out.println("Ivalid password or username..");
}

newf obj = new new(); - It is a new form that should be displayed if password and
username is correct

Note: object newf is a another form that is open when the password and username are correct.

84 | P a g e Moses Wainaina - 0707691430


To add two numbers
Create The following Form

Double Click on Button Add and write the following code


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { (after this line
copypaste these codes)
int fastnumber = Integer.parseInt(fast.getText());
int secondnumber = Integer.parseInt(second.getText());
int total = fastnumber+secondnumber;
sum.setText(" "+total);

85 | P a g e Moses Wainaina - 0707691430


Double click on clear button and write the following code
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
fast.setText(null);
second.setText(null);
sum.setText(null);

86 | P a g e Moses Wainaina - 0707691430

You might also like