CSC 313
CSC 313
CSC 313
1
1.0 MODULE ONE
A programming tool or software development tool is a computer program that software developers use to create,
debug, maintain, or otherwise support other programs and applications. The term usually refers to relatively
simple programs, that can be combined together to accomplish a task, much as one might use multiple
hand tools to fix a physical object. The ability to use a variety of tools productively is one hallmark of a
skilled software engineer.
The most basic tools are a source code editor and a compiler or interpreter, which are used ubiquitously and
continuously. Other tools are used more or less depending on the language, development methodology, and
individual engineer, and are often used for a discrete task, like a debugger or profiler. Tools may be discrete
programs, executed separately – often from the command line – or may be parts of a single large program, called
an integrated development environment (IDE). In many cases, particularly for simpler use, simple ad hoc
techniques are used instead of a tool, such as print debugging instead of using a debugger, manual timing (of
overall program or section of code) instead of a profiler, or tracking bugs in a text file or spreadsheet instead of
a bug tracking system.
Integrated development environments combine the features of many tools into one package. They for example
make it easier to do specific tasks, such as searching for content only in files in a particular project. IDEs may for
example be used for development of enterprise-level applications.
There are software development tools web sites that list commercial and open source software tools related to all
areas of software development: programming editors and frameworks (Java, .NET, PHP, C#, JavaScript, Ruby,
Ajax, etc.), project management, Agile, Scrum, Kanban, UML, software testing, databases, configuration
management,
In Java, programs are not compiled into executable files; they are compiled into bytecode , which the JVM (Java
Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we use the java
compiler. The bytecode gets saved on the disk with the file extension .class. When the program is to be run, the
bytecode is converted, using the just-in-time (JIT) compiler. The result is machine code which is then fed to the
memory and is executed.
2
Java code needs to be compiled twice in order to be executed:
The Java classes/bytecode are compiled to machine code and loaded into memory by the JVM when needed the
first time. This is different from other languages like C/C++ where programs are to be compiled to machine code
and linked to create an executable file before it can be executed.
Compiler is a computer program (or a set of programs) that transfers source code written in programming
language( the source language) into another computer language (the target language), with the latter often known
as object code. It can also be seen as a special program that processes statements written in a particular
programming language and turns them into machine language or “code” that a computer’s processor uses.
Interpreter is a computer program that directly executes , that is, performs, instruction written in a programming
or scripting language, without previously compiling them into a machine language program
Explanation :
1. We give complete program as input to the compiler. Our program is in the human readable format.
2. Human readable format undergoes many passes and phases of compilerand finally it is converted into the
machine readable format.
3. However interpreter takes single line of code as input at a time and execute that line. It will terminate the
execution of the code as soon as it finds the error.
4. Memory requirement is less in Case of interpreter because no object code is created in case of interpreter.
The main difference between an interpreter and a compiler is that compilation requires analysis and the
generation of machine code only once, whereas an interpreter may need to analyse and interpret the same
program statements each time it meets them e.g. instructions appearing within a loop. For example the following
Visual Basic code would be interpreted each time the loop is entered:
3
For iCountvar = To 20
iSum = iSum + iCountvar
Pic.Display iSum
Next iCountvar
This has implications for error reporting, eg: when an interpreter encounters an error it reports it to the user
immediately and halts further execution of the program. Such instant feedback, pinpointing the exact location of
the error, helps the programmer to find and remove errors.
Compilers, on the other hand, analyse the entire program, taking note of where errors have occurred, and places
these in an error/diagnostic file. If errors have occurred then the program cannot run. Programmers must then use
the error messages to identify and remove the errors in the source code. Some compilers assist by adding line
numbers to the source listing to help pinpoint errors and all compilers will describe the nature of the error e.g.
missing semi-colon, expected keyword, etc. - although interpreting some compiler diagnostics is a skill in itself.
Error correction can be very time-consuming and frustrating, particularly in the case where spurious errors occur,
e.g. many errors are highlighted in the source but the cause of the error is a single, simple mistake. An example of
this would be errors that are generated by, say, a compiler, if a programmer simply misses out a semi-colon.
Another important difference is that interpreters can be 2 to 10 times slower than compilers. One reason for this is
that they translate the same statements within a loop over and over again. Compilers can produce much more
efficient object code than interpreters thus making the compiled programs to run faster.
Interpreters however are easier to use, particularly for beginners, since errors are immediately displayed,
corrected by the user, until the program is able to be executed. On the whole compilers tend to be more difficult
to use.
4
Creating Your First Application
/**
* The JabuUniversity class implements an application that
* simply prints "JabuUniversity d!" to standard output.
*/
class JabuUniversity App {
public static void main(String[] args) {
System.out.println("JabuUniversity!"); // Display the string.
}
}
Your first application, JabuUniversity App, will simply display the greeting "JabuUniversity !". To create this
program.
A source file contains code, written in the Java programming language, that you and other programmers
can understand. You can use any text editor to create and edit source files.
The Java programming language compiler (javac) takes your source file and translates its text into
instructions that the Java virtual machine can understand. The instructions contained within this file are
known as bytecodes.
The Java application launcher tool (java) uses the Java virtual machine to run your application.
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
5
System.out.println("Hello World!"); // Display the string.
}
}
System.out.println(root1);
System.out.println(root2);
}
}
Programming in Java. We break the process of programming in Java into three steps:
Create the program by typing it into a text editor and saving it to a file named, say, MyProgram.java.
Compile it by typing "javac MyProgram.java" in the terminal window.
Run (or execute) it by typing "java MyProgram" in the terminal window.
The first step creates the program; the second translates it into a language more suitable for machine execution
(and puts the result in a file named MyProgram.class); the third actually runs the program.
Creating a Java program. A program is nothing more than a sequence of characters, like a sentence, a paragraph,
or a poem. To create one, we need only define that sequence characters using a text editor in the same way as we
do for e-mail. HelloWorld.java is an example program. Type these character into your text editor and save it into
a file named HelloWorld.java.
public class HelloWorld {
6
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Compiling a Java program. At first, it might seem to you as though the Java programming language is designed to
be best understood by the computer. Actually, to the contrary, the language is designed to be best understood by
the programmer (that's you). A compiler is an application that translates programs from the Java language to a
language more suitable for executing on the computer. It takes a text file with the .java extension as input (your
program) and produces a file with a .class extension (the computer-language version). To compile
HelloWorld.java type the boldfaced text below at the terminal. (We use the % symbol to denote the command
prompt, but it may appear different depending on your system.)
% javac HelloWorld.java
If you typed in the program correctly, you should see no error messages. Otherwise, go back and make sure you
typed in the program exactly as it appears above.
Executing a Java program. Once you compile your program, you can run it. This is the exciting part, where the
computer follows your instructions. To run the HelloWorld program, type the following at the terminal:
% java HelloWorld
If all goes well, you should see the following response
Hello, World
Understanding a Java program. The key line with System.out.println() send the text "Hello, World". When we
begin to write more complicated programs, we will discuss the meaning of public, class, main, String[], args,
System.out, and so on.
Creating your own Java program. For the time being, all of our programs will be just like HelloWorld.java,
except with a different sequence of statements in main(). The easiest way to write such a program is to:
Copy HelloWorld.java into a new file whose name is the program name followed by .java.
Replace HelloWorld with the program name everywhere.
Replace the print statement by a sequence of statements.
Errors. Most errors are easily fixed by carefully examining the program as we create it, in just the same way as
we fix spelling and grammatical errors when we type an e-mail message.
Compile-time errors. These errors are caught by the system when we compile the program, because they prevent
the compiler from doing the translation (so it issues an error message that tries to explain why).
Run-time errors. These errors are caught by the system when we execute the program, because the program tries
to peform an invalid operation (e.g., division by zero).
Logical errors. These errors are (hopefully) caught by the programmer when we execute the program and it
7
produces the wrong answer. Bugs are the bane of a programmer's existence. They can be subtle and very hard to
find.
1.3 DaTa TYpe
A data type is a set of values and a set of operations defined on them. For example, we are familiar with numbers
and with operations defined on them such as addition and multiplication (in mathematics, we are accustomed to
thinking of the set of numbers as being infinite; in computer programs we have to work with a finite number of
possibilities).
There are eight different built-in types of data in Java, mostly different kinds of numbers. Other types are
available in system libraries, and programming in Java is actually centered around building our own data types,
as we shall see later. We use the system type for strings of characters so frequently that we also consider it here.
Basic definitions. We use the following four statement Java program fragment to introduce some terminology
that we'll be using:
int a, b, c;
a = 1234;
b = 99;
c = a + b;
The first statement declares three variables with the identifiers a, b, and c to be of type int. The next
two assignment statements change the values of the variables, using the literals 1234 and 99. The final statement
assigns c to have the value 1333 by evaluating the expression a + b.
Characters and Strings. A char is an alphanumeric character or symbol, like the ones that you type. We usually do
not perform any operations on characters other than assigning values to variables. A String is a sequence of
characters. The most common operation that we perform on strings is known asconcatenation: given two strings,
chain them together to make a new string. For example, consider the following Java program fragment:
String a, b, c;
a = "Hello,";
b = " Bob";
c = a + b;
The first statement declares three variables to be of type String. The next three statements assign values to them,
with the end result that c has the value"Hello, Bob". Using string concatenation, Program Ruler.java prints the
relative lengths of the subdivisions on a ruler.
8
Integers. An int is an integer (whole number) between -231 and 231 - 1 (-2,147,483,648 to 2,147,483,647). We
use ints frequently not just because they occur frequently in the real world, but also they naturally arise when
expressing algorithms. Standard arithmetic operators for addition, multiplication, and division, for ints are built in
to Java, as illustrated in IntOps.java.
The type long is similar to int except it can represent integers in a much larger ranger, between -263 an 263 - 1. We
occasionally use long when we need to work with huge integers.
Real numbers. The double type is for representing floating-point numbers, e.g., for use in scientific applications.
The internal representation is like scientific notation, so that we can compute with real numbers in a huge range.
We can specify a floating point number using either a string of digits with a decimal point, e.g., 3.14159 for a 6
six digit approximation to the mathematical constant pi, or with a notation like scientific notation,
e.g., 6.022E23 for Avogadro's constant 6.022 × 1023. Standard arithmetic operators for addition, multiplication,
and division, for doubles are built in to Java, as illustrated in DoubleOps.java. ProgramQuadratic.java shows the
use of doubles in computing the two roots of a quadratic equation using the quadratic formula. The
Java Math library defines trigonometric functions, logarithm/exponential, and other common functions for
doubles. Trig.java illustrates a number of trigonometric functions includingMath.sin(), Math.cos(),
and Math.toRadians().
Booleans. The boolean type has just two values: true or false. The apparent simplicity is deceiving - booleans lie
at the foundation of computer science. The most important operators defined for booleans are for and, or,
and not.
and: a && b is true if both a and b are true, and false otherwise.
or: a || b is true if either a or b is true (or both are true), and false otherwise
Although these definitions are intuitive and easy to understand, it is worthwhile to fully specify each possibility
for each operation in a truth table.
a b a && b a || b
Comparisons. The comparison operators are mixed-type operations that take operands of one type
(e.g., int or double) and produce a result of typeboolean. These operations play a critical role in the process of
developing more sophisticated programs.
== equal to a is equal to b 2 == 2 3 == 2
LeapYear.java tests whether an integer corresponds to a leap year in the Gregorian calendar. Here's is Stanley
Rabinowitz's entertaining response to a question as to why OpenVMS assumes that 2000 is a leap year.
Type conversion.
We often find ourselves converting data from one type to another using one of the following approaches.
Automatic type conversion. For primitive numeric types, the system automatically performs type
conversion when we use a value whose type has a larger range of values than expected.
10
Explicit casts. Java also has some built-in type conversion methods for primitive types that you can use
when you are aware that you might lose information, but you have to make your intention using
something called a cast. Program RandomInt.java reads in a command-line argument N and prints out a
"random" integer between 0 and N-1.
Automatic conversions for strings. The built-in type String obeys special rules. One of these special rules
is that you can easily convert any type of data to a String by using the + operator.
11
CHAPTER TWO
This happens when a program starts with a problem and then breaks that problem down into smaller sub-
problems or sub-procedures. These sub-procedures are continually broken down in the process called functional
decomposition until the sub-procedure is simple enough to be solved.
The issue that is obvious in PROCEDURAL PROGRAMMING is that if a edit is needed to the program, the
developer must edit every line of code that corresponds to the original change in the code
In order to clearly understand the object orientation model, let’s take your “hand” as an example. The “hand” is a
-[class. Your body has two objects of the type "hand", named "left hand" and "right hand". Their main functions
are controlled or managed by a set of electrical signals sent through your shoulders (through an interface). So the
shoulder is an interface that your body uses to interact with your hands. The hand is a well-architected class. The
hand is being reused to create the left hand and the right hand by slightly changing the properties of it.
Object Oriented Programming is dividing a task into objects which have behaviors (methods) specified which act
upon their data (members).
In POP, program is divided into small parts called functions. In OOP, program is divided into parts called objects.
In POP,Importance is not given to data but to functions as well as sequence of actions to be done. In OOP,
Importance is given to the data rather than procedures or functions because it works as a real world.
POP follows Top Down approach. OOP follows Bottom Up approach.
POP does not have any access specifier. OOP has access specifiers named Public, Private, Protected, etc.
In POP, Data can move freely from function to function in the system. In OOP, objects can move and
communicate with each other through member functions.
To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function.
In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the
system. In OOP, data can not move easily from function to function,it can be kept public or private so we can
control the access of data.
POP does not have any proper way for hiding data so it is less secure. OOP provides Data Hiding so
provides more security.
The problem with procedural programming is that code reusability is hard and limited – only procedures can be
reused and it is hard to make them generic and flexible.
In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function
examples of real-world objects: your dog, your desk, your television set, your bicycle.
13
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color,
breed, hungry) and behavior (barking, fetching, wagging tail).
The main advantages and goals of OOP are to make complex software faster to develop and easier to maintain.
OOP enables the easy reuse of code by applying simple and widely accepted rules (principles
14
3.0 Basic Concepts of OOP
3.1. OBJECT
An object is a software bundle of related state and behavior. Software objects are often used to model the real-
world objects that you find in everyday life
Objects are the basic unit of OOP. They are instances of class, which have data members and uses various
member functions to perform tasks.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the
object performs defines the object's behavior. For example, the Hand (object) can grip something, or
a Student(object) can give their name or address.
Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many objects
around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging,
running. If you compare the software object with a real world object, they have very similar
characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and behavior
is shown via methods. So in software development, methods operate on the internal state of an object
and the object-to-object communication is done via methods
void barking(){
}
void hungry(){
}
void sleeping(){
}}
15
3.2 CLASS
A class is simply a representation of a type of object. It is the blueprint, or plan, or template, that describes the
details of an object. A class is the blueprint from which the individual objects are created. Class is composed of
three things: a name, attributes, and operations.
Class - A class can be defined as a template/blue print that describes the behaviors/states that object of
its type support.
According to the sample given below we can say that the Student object, named objectStudent, has been
created out of the student class
In real world, you'll often find many individual objects all of the same kind. As an example, there may be
thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same
blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as
bicycles.
Also, It is similar to structures in C language. Class can also be defined as user defined data type but it also
contains functions in it. It declare & defines what data variables the object will have and what operations can be
performed on the class's object.
A class is a blue print from which individual objects are created. A sample of a class is given in object
above
16
Local variables: Variables defined inside methods, constructors or blocks are called local variables.
The variable will be declared and initialized within the method and the variable will be destroyed
when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These
variables are initialized when the class is instantiated. Instance variables can be accessed from inside
any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method, with the static
keyword.
A class can have any number of methods to access the value of various kinds of methods. In the above
example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when looking into classes
of the Java Language.
3.3 Constructors:
When discussing about classes, one of the most important sub topic would be constructors. Every class
has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a
default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically an object is created
from a class. In Java, the new key word is used to create new objects.
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the
new object.
If we compile and run the above program, then it would produce the following result:
3.4. ENCAPSULATION
Encapsulation is placing the data and the functions that work on that data in the same place.
Encapsulation is:
Binding the data with the code that manipulates it.
It keeps the data and the code safe from external interference
The idea of encapsulation is to keep classes separated and prevent them from having tightly coupled with
each other.
Encapsulation cab as be viewed as hiding irrelevant data from the user. A class may contain much
information that is not useful for an outside class or interface. The idea behind this concept is “Don’t tell
me how you do it. Just do it.”. So classes use encapsulation to hide its members that are not relevant for
an outside class or interface. Encapsulation can be done using access specifiers
The encapsulation is the inclusion-within a program object-of all the resources needed for the object to function,
basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes
expose public methods and properties. A class is kind of a container or capsule or a cell, which encapsulate a set
of methods, attribute and properties to provide its indented functionalities to other classes. In that sense,
18
encapsulation also allows a class to change its internal implementation without hurting the overall functioning of
the system. That idea of encapsulation is to hide how a class does its business, while allowing other classes to
make requests of it.
Encapsulation is about placing the data and the functions that work on that data in the same place.
While working with procedural languages, it is not always clear which functions work on which variables but
object-oriented programming provides you framework to place the data and the relevant functions together in the
same object.
Encapsulation is the packing of data and functions into a single component. The features of encapsulation are
supported using classes in most object-oriented programming languages, although other alternatives also exist. It
allows selective hiding of properties and methods in an object by building an impenetrable wall to protect the
code from accidental corruption.
Encapsulation can be used to hide data member and member function. Under this definition, encapsulation means
that the internal representation of an object is generally hidden from view outside of the object's definition
Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the
component into an invalid or inconsistent state. A supposed benefit of encapsulation is that it can reduce system
complexity, and thus increase robustness, by allowing the developer to limit the inter-dependencies between
software components
It is the principle of information hiding. That is, the implementation (the internal workings) of an object is hidden
from the rest of the program.
A popular example you’ll hear for encapsulation is driving a car. Do you need to know exactly how every aspect
of a car works (engine, carburettor, alternator, and so on)? No - you need to know how to use the steering wheel,
brakes, accelerator, and so on.
Encapsulation helps to create code that is loosely coupled. Because the details are hidden, it reduces the ability of
other objects to directly modify an object's state and behavior.
Encapsulation can help to create more maintainable code by helping to prevent the ripple effect of code changes.
It also helps with creating loosely coupled code by reducing direct access to an object's state and behavior.
Below is an example in C# that shows how access to a data field can be restricted through the use of
a private keyword:
class Program {
public class Account {
private decimal accountBalance = 500.00m;
/* This Main method can check the balance via the public
* "CheckBalance" method provided by the "Account" class
* but it cannot manipulate the value of "accountBalance" */
}
}
3.5 INHERITANCE
Inheritance is a way to reuse once written code again and again. The class which is inherited is called base calls
& the class which inherits is called derived class. So when, a derived class inherits a base class, the derived class
can use all the functions which are defined in base class, hence making code reusable.
One of the most useful aspects of object-oriented programming is code reusability. As the name suggests
Inheritance is the process of forming a new class from an existing class that is from the existing class called as
base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce the code size.
In object-oriented programming, inheritance enables new objects to take on the properties of existing objects. A
class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a
superclass is called a subclass or derived class. The terms parent class and child class are also acceptable terms
to use respectively. A child inherits visible properties and methods from its parent while adding additional
properties and methods of its own.
20
Using two concepts of inheritance, subclassing (making a new class based on a previous one) and overriding
(changing how a previous class works), you can organize your objects into a hierarchy. Using inheritance to
make this hierarchy often creates easier to understand code, but most importantly it allows you to reuse and
organize code more effectively
It allows a class to "inherit" (behavior or characteristics) of another, more general class. For example, a lion
belongs to the biological family of cats (Felidae). All cats that have four paws, are predators and hunt their prey.
This functionality can be coded once in the Felidae class and all its predators can reuse it – Tiger, Puma, Bobcat,
etc. Inheritance is described as is-kind-of relationship, e.g. Tiger is kind ofAnimal.
Felidae.cs
21
Lion.cs
According to the above example the new class (IOException), which is called the derived class or subclass,
inherits the members of an existing class (Exception), which is called the base class or super-class. The
classIOException can extend the functionality of the class Exception by adding new types and methods and by
overriding existing ones.
22
3.6 Base & Derived Classes:
A class can be derived from more than one classes, which means it can inherit data and functions from multiple
base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class
derivation list names one or more base classes and has the form:
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined
class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream>
using namespace std;
// Base classclass Shape {
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;};
// Derived classclass Rectangle: public Shape{
public:
int getArea()
{
return (width * height);
}};
int main(void){
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;}
When the above code is compiled and executed, it produces the following result:
23
3.7 POLYMORPHISM
This is an object-oriented programming concept that refers to the ability of a variable, function or object to take
on multiple forms. In a programming language that exhibits polymorphism, objects of classes belonging to the
same hierarchical tree (i.e. inherited from a common base class) may possess functions bearing the same name,
but each having different behaviors.
As an example, let us assume there is a base class named Animals from which the subclasses Horse, Fish and
Bird are derived. Let us also assume that the Animals class has a function named Move, which is inherited by all
subclasses mentioned. With polymorphism, each subclass may have its own way of implementing the function.
So, for example, when the Move function is called in an object of the Horse class, the function might respond by
displaying trotting on the screen. On the other hand, when the same function is called in an object of the Fish
class, swimming might be displayed on the screen. In the case of a Bird object, it may be flying.
Polymorphism means one name, many forms. Polymorphism manifests itself by having multiple methods all
with the same name, but slighty different functionality.
Polymorphism describes a pattern in object oriented programming in which classes have different functionality
while sharing a common interface.
The beauty of polymorphism is that the code working with the different classes does not need to know which
class it is using since they’re all used the same way. A real world analogy for polymorphism is a button.
Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends
on what it is connected to and the context in which it is used — but the result does not affect how it is used. If
your boss tells you to press a button, you already have all the information needed to perform the task.
Plymorphism refers to a programming language's ability to process objects differently depending on their data
type or class. More specifically, it is the ability to redefine methods forderived classes. For example, given a base
class shape,polymorphism Zenables the programmer to define different area methods for any number of derived
classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to
it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented
programming language (OOPL).
Polymorphism means one name, many forms. Polymorphism manifests itself by having multiple methods all with
the same name, but slightly different functionality.
24
In summary,Polymorphism
The ability to use an operator or function in different ways in other words giving different meaning or
functions to the operators or functions is called polymorphism. Poly refers to many. That is a single
function or an operator functioning in many ways different upon the usage is called polymorphism.
In other words it means, one method with multiple implementation, for a certain class of action. And
which implementation to be used is decided at runtime depending upon the situation (i.e., data type
of the object)
This can be implemented by designing a generic interface, which provides generic methods for a
certain class of action and there can be multiple classes, which provides the implementation of these
generic methods.
Overloading in simple words means two methods having same method name but takes different
input parameters. This called static because, which method to be invoked will be decided at the time
of compilation
Overriding means a derived class is implementing a method of its super class.
Overridding, also called run-time polymorphism. For method overloading, the compiler determines which
method will be executed, and this decision is made when the code gets compiled.
Overloading, which is referred to as compile-time polymorphism. Method will be used for method overriding is
determined at runtime based on the dynamic type of an object.
Lets us look at same example of a car. A car have a gear transmission system. It has four front gears and one
backward gear. When the engine is accelerated then depending upon which gear is engaged different amount
power and movement is delivered to the car. Polymorphism could be static and dynamic both. Overloading is
static polymorphism while, overriding is dynamic polymorphism.
25
Overriding and Overloading are two very important concepts in Java. They are confusing for Java novice
programmers. This post illustrates their differences by using two simple examples.
1. Definitions
Overloading occurs when two or more methods in one class have the same method name but different
parameters.
Overriding means having two methods with the same method name and parameters (i.e.,method si gnature). One
of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a
specific implementation of a method that is already provided its parent class.
1. Real object type, not the reference variable's type, determines which overridden method is used at runtime. In
contrast, reference type determines which overloaded method will be used atcompile time.
2. Polymorphism applies to overriding, not to overloading.
3. Overriding is a run-time concept while overloading is a compile-time concept.
3. An Example of Overriding
Here is an example of overriding. After reading the code, guess the output.
class Dog{
public void bark(){
26
System.out.println("woof ");
}}class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}
bowl
In the example above, the dog variable is declared to be a Dog. During compile time, the compiler checks if
the Dog class has the bark() method. As long as the Dog class has thebark() method, the code compilers. At run-
time, a Hound is created and assigned to dog. The JVM knows that dog is referring to the object of Hound, so it
calls the bark() method ofHound. This is called Dynamic Polymorphism.
4. An Example of Overloading
class Dog{
public void bark(){
System.out.println("woof ");
}
//overloading method
public void bark(int num){
for(int i=0; i<num; i++)
System.out.println("woof ");
}}
In this overloading example, the two bark method can be invoked by using different parameters. Compiler know
they are different because they have different method signature (method name and method parameter list).
27
use common interface and rely on concrete implementation, we always need to change and duplicate most of our
code to support new implementation. Its not only Java but other object oriented language like C++ also supports
polymorphism and it comes as fundamental along with other OOPS concepts like Encapsulation , Abstraction
and Inheritance.
Here we have a super class called TradingSystem and there two implementation DirectMarketAccessSystem and
CommodityTradingSystem and here we will write code which is flexible enough to work with any future
implementation of TradingSystem we can achieve this by using Polymorphism in Java which we will see in
further example.
3.10 ABSTRACTION
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a powerful methodology to
manage complex systems. Abstraction is managed by well-defined objects and their hierarchical
classification. For example a car in itself is a well-defined object, which is composed of several other
smaller objects like a gearing system, steering mechanism, engine, which are again have their own
subsystems. But for humans car is a one single object, which can be managed by the help of its
subsystems, even if their inner details are unknown.
As per dictionary, Abstraction is the quality of dealing with ideas rather than events. for example when
you consider the case of e-mail, complex details such as what happens soon you send an e-mail, the
protocol your email server uses are hidden from the user, therefore to send an e-mail you just need to
like wise in Object oriented programming Abstraction is a process process of hiding the implementation
details from the user, only the functionality will be provided to the user. In other words user will have
the information on what the object does instead of how it does it.
29
Data abstraction refers to, providing only essential information to the outside world and hiding their
background details, i.e., to represent the needed information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and maintained.
Abstraction is defined as showing only the relevant data to the user. Generally abstraction and
encapsulation are explained in confusing manners.
Relevant Features of a phone in which the user is interested are Camera, Music player, Calling function,
Voice recording and so on.
Irrelevant Features of a phone in which the user is not interested are circuit board design, hardware used
and so on.
So in designing the Mobile Phone Model, both relevant and irrelevant features are required. But we need
to show only relevant features. So we design a Mobile Phone in such a way that only relevant features
are shown and irrelevant features are hidden. And remember one thing, that deciding relevant and
irrelevant features is totally a user choice
When a class is conceptualized, what are the properties we can have in it given the context. If we are
designing a class Animal in the context of a zoo, it is important that we have an attribute as animalType
to describe domestic or wild. This attribute may not make sense when we design the class in a different
context.
Similarly, what are the behaviors we are going to have in the class? Abstraction is also applied here.
What is necessary to have here and what will be an overdose? Then we cut off some information from
the class. This process is applying abstraction.
When we ask for difference between encapsulation and abstraction, I would say, encapsulation uses
abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept applied as
part of inheritance and polymorphism.
We got to look at abstraction at a level higher among the other OOP concepts encapsulation, inheritance
and polymorphism.
30
Point x = { 1, 8 } ;
Point y = {34, 87 }
Int d = distance(x, y) ; Here, distance encapsulates the calculation between two points in a plane; it
hides implementation details. Abstraction is the process of generalization, that is, taking a concrete
implementation and making it apllicable to different related data type. A classical ex of abstraction is
qsort funtion whgich sorts data in C’s. One thing about qsort is that it doesnt care about the data is
sorting. Infact it doesnt know which data is sorts
Abstraction is when we hide the implementation level details from the users and give access to only
necessary values only like sum (1,56), we have abstracted the process of sum from the user
Abstraction lets you u focus on what the object does instead of how it doesit
Encapsulation means hidig the internal details or mechanics of how an object does something. Like
when you drive, you know what the gas pedal does but you mat not know the process behind because it
is encapsulated.
In summary, Encapsulation is the packing of data and functions operating on that data into a single
component and restricting tha access to some of object’s component. It means that the internal
representation of an object is generally hidden from view outside of the object’s defintion
Abstraction is a mechanism which represent the essential features without including implemetion details
Another school of thought believe that we do abstraction when deciding what to implement. We do encapsulate
when hiding something that you have implemented. Abstraction is implemented in Java using interface and
abstract class while encapsulation is implemented using private, package-private and protected access modifier
31
4.0 MODULE FOUR
ASSESSMENT (JAVA) PRACTICAL
PRACTICAL QUESTIONS
QUESTION 1
In a supermarket at Joseph Ayo Babalola University Shopping mall in December, the following discount
prices were given as Xmas bonanzas for purchasing High Malt, which cost N55 per one by that time:
6 – 10 7%
11 – 19 12%
Write a program to compute the net payable by a customer after discount has been deducted for its initial
total payable.
QUESTION 2
Write a program snippet to find the average value of data stored in a one dimensional array.
QUESTION 3
The factorial of N is given as N x (N-1) x (N-2) x …. x 2 x 1. Write a Java program to compute the value
of any given integer.
QUESTION 4
Write a Java program that will compute your final Cumulative Grade Point Average (CGPA) of any
student in Joseph Ayo Babalola University.
QUESTION 5
Write a Java Program to compute the root of any quadratic equation.
QUESTION 6
Write a Java program to compute the standard deviation of any numbers
QUESTION 7
Write a program to compute the sum of two matrices of n X m dimensions using nested for loops.
32
QUESTION 8
In an experiment to find the relationship between tensile strength, T of a material and its length, x , the
mathematical relationship below results:
Y =x3 – sin2x
√cos x – x
QUESTION 10
Write a program to compute the squares, square roots, cube and cube roots of all numbers from 1 to n, where n
is a valid positive integer. The program must be well tabulated with appropriate headings.
QUESTION 11
Write a Java program snippet for a method that returns the maximum of three numbers.
QUESTION 12
Write a recursive Java method to return the factorial of a number, n.
QUESTION 13
Write a function in Java that could accept an integer denoting a year and returns true or false according to
whether the year is a leap year or not.
QUESTION 14
Write a function in Java that accepts two dates in a year and computes the number of days between them.
State the conditions under which the function may work properly (regarding the ordering of input to the
function).
QUESTION 15
Develop an applet that reads in the radius of a circle and draws its diameter, area and circumference
QUESTION 16
Develop an applet that accepts five integers from the keyboards and determines largest and smallest in the
group.
QUESTION 17
Develop an applet that calculates the squares and cubes of numbers from 0 to 10 and draws the resulting values in
table format as shown below
number square cube
0 0 0
33
1 1 1
2 4 8
QUESTION 18
Write a Java program that reads integers from keyboard into a two-dimensional irregular array shown below
and write them out in the order k, j, i, h, g, f, a, b, c, d, e.
e d c b a
f
g h i
QUESTION 19
Write a complete JAVA program that reads the score and decides the students CGPA in the computation of
students scores for all courses registered by a student at the end of an academic session according to the
following rules
≥70 – 7 points
65-69 – 6 points
60-64 - 5 points
55-59 - 4 points
50-54 - 3 points
45-49 – 2 points
40-44 – 1 point
0-39 – 0 point
Write an IF Contruct that will assign grades as described above using BOTH
a) ELSE IF Construct
b) NESTED IF Construct
QUESTION 20
It is often hard to compare the value of two items if they are priced in different currencies. Write a JAVA
program that will allow a user to enter the cost of a purchase in U.S. dollars, Australian dollars, Euros or
U.K pounds and then convert the cost into any of the other currencies as specified by the user. Use the
following conversion factors in your program:
34
A$1.00 = US$0.74
€1.00 = US$1.21
UK€1.00 = US$1.78
QUESTION 21
Write a JAVA program to read any values from an input data file and calculate their Range, Mean, Mode,
Median, Mean deviation, Variance and Standard deviation.
QUESTION 22
Matrix Multiplication: Matrix multiplication is only defined for two matrices in which the number of columns in
the first matrix is equal to the number of rows in the second matrix. If matrix A is an N * L matrix and matrix B is
an L * M matrix, then the product C = A*B is an N*M matrix whose elements are given by the equation
Cik = ∑ aijbjk
For example, if matrices A and B are 2x2 matrices
35
a data set of real numbers in an array.
The set of subroutines should include:
a) A subroutine to determine the maximum value in a data set and the sample number containing that
value.
b) A subroutine to determine the minimum value in a data set and the sample number containing that
value.
c) A subroutine to determine the average (mean) and standard deviation of the data set.
QUESTION 24
Write and run a java program that generates a random integer in the range 0 to 99 inclusive, and then tests and
reports whether it is even or odd and also determine their minimum and maximum value.
QUESTION 25
Write and run a java program that generates three random floats and then prints them in their ascending order.
REFERENCES:
BOOKS:
36