OOP Chapter 1
OOP Chapter 1
OOP Chapter 1
An object-oriented approach identifies the keywords in the problem. The keywords would be the object in
the implementation and the hierarchy defines the relationship between these objects. The term object is
used here to describe a limited well-defined structure, containing all the information about some entity -
data type and methods to manipulate the data.
Why do we use Object-Oriented Programming?
OOP enable us to model real-world problem through programs in more logical manner - Because objects
are discrete entities, we can debug, modify and maintain them more easily - If our objects are thoughtfully
designed, we can reuse much of our code than is the case with procedural programming. OOP is the most
usable and maintainable programming due to the following basic features.
Encapsulation
A goal of OOP is to differentiate the use of an object from the implementation of that object. One method to
accomplish this is through the usage of data binding/hiding. Data hiding enable us to completely encapsulate
an object’s data members.
Inheritance
Inheritance is a technique for creating a new class (subclass) from an existing class (superclass) by
adding more functionality to it. We say that the new class inherits all the functionality from the existing
class.
A subclass is derived from a superclass. Example: An Employee is a Person.
The subclass inherits the attributes and behavior of the superclass.
The subclass can override the behavior of the superclass.
Inheritance supports code re-use.
Polymorphism
The term polymorphism is derived from a Greek term meaning many form use of a single method.
A method can have many different forms of behavior.
A single method may be defined upon more than one class and may take on different
implementations in each of those classes.
Message passing
Objects communicate by sending messages.
Messages convey some form of information.
An object requests another object to carry out an activity by sending it a message.
Most messages pass arguments back and forth through the object using dot operator.
Classes
A class is user-defined data type that is used to implement an abstract object, giving us the capability to
use OOP. A class includes members. A member can be either data known as a data member or a method,
known as a member method.
Members of a class
A class has one or more variable types, called members. The two types of members are data members and
methods member.
Data members: data members of a class are exactly variables.
Methods member: are methods/ functions defined within a class that act on the data members in the class.
Example:
class student {
String Stud_name; // data members
String Stud_IDNo;
int Age;
public static void main(String[] args) { // Main function
student stud;
stud.Stud_name=”Abel”;
stud.Age=24;
System.out.println(stud.Stud_name); //methods member
System.out.println(stud.Age);
System.out.println(“This is your first java code!”);
}}
Assignment
1. What is Programming language, what is the use of programming languages? Give some examples of
programming language and classify them as OOP and non-OOP language.
2. Discuss the advantage of object-oriented programming language (OOP) over non-OOP languages
(Unstructured and Structured Programming language).
What is Java?
Java is a computer programming language created by Sun Microsystems. Java is used mainly on the Internet
and uses a virtual machine which has been implemented in most browsers to translate Java code into a
Object oriented
Portable
Distributed
Multithreaded
Java is a popular programming language, created in 1995.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
And much, much more!
A JVM is distributed along with a set of standard class libraries that implement the Java application
programming interface (API). Appropriate APIs bundled together form the Java Runtime Environment
(JRE).
JVMs are available for many hardware and software platforms. The use of the same bytecode for all JVMs
on all platforms allows Java to be described as a "compile once, run anywhere" programming language, as
opposed to "write once, compile anywhere", which describes cross-platform compiled languages. Thus,
the JVM is a crucial component of the Java platform.
As long as a computer has a Java VM (Virtual Machine), a Java program can run on these machines,
Windows 2000
Linux
Solaris
MacOS
The JDK (Java Development Kit) is used for developing java applications. The JDK includes JRE, set of
API classes, Java compiler, Webstart and additional files needed to write Java applications. The JDK
(Java Development Kit) contains software development tools which are used to compile and run the Java
program. Both JDK and JRE contain the JVM.
Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment (JRE) is an
implementation of the JVM. Java Development Kit (JDK) contains JRE along with various development
tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.
JVM becomes an instance of JRE at runtime of a java program. It is widely known as a runtime
interpreter. The Java virtual machine (JVM) is the cornerstone on top of which the Java technology is built
upon. It is the component of the Java technology responsible for its hardware and platform independence.
In general java is:
An OOP that uses class and objects.
A very portable object-oriented programming language
This command is an example of a subroutine call statement. It uses a "built-in subroutine/method" named
System.out.println( ) to do the actual work. Recall that a subroutine consists of the instructions for
performing some task, chunked together and given a name. That name can be used to "call" the subroutine
whenever that task needs to be performed. A built-in subroutine is one that is already defined as part of the
language and therefore is automatically available for use in any program.
When you run this program, the message "Hello World!" (Without the quotes) will be displayed on
standard output. The computer will type the output from the program, Hello World!
You must be curious about all the other stuff in the above program. Part of it consists of
comments. Comments in a program are entirely ignored by the computer; they are there for human
readers only. This doesn't mean that they are unimportant. Programs are meant to be read by
people as well as by computers, and without comments; a program can be very difficult to
understand. Java has two types of comments. The first type, used in the above program, begins
with // and extends to the end of a line. The computer ignores the // and everything that follows it
on the same line. Java has another style of comment that can extend over many lines. That type of
comment begins with /* and ends with */.
Everything else in the program is required by the rules of Java syntax. All programming in Java is
done inside "classes." The first line in the above program (not counting the comments) says that
this is a class named HelloWorld. "HelloWorld," the name of the class, also serves as the name of
When you tell the Java interpreter to run the program, the interpreter calls the main( ) subroutine, and the
statements that it contains are executed. These statements make up the script that tells the computer
exactly what to do when the program is executed. The main() routine can call subroutines that are defined
in the same class or even in other classes, but it is the main() routine that determines how and in what
order the other subroutines are used.
The word "public" in the first line of main() means that this routine can be called from outside the
program. This is essential because the main() routine is called by the Java interpreter, which is something
external to the program itself. Static indicates that main() is a class method not an instance method ,it is
static.
The definition of the subroutine -- that is, the instructions that say what it does -- consists of the sequence
of "statements" enclosed between braces, { }. A program is defined by a public class that takes the form:
Variables
What is variable in the concept of programming language?
Programs manipulate data that are stored in memory. In a high-level language such as Java, names are
used to refer to data. It is the job of the computer to keep track of where in memory the data is actually
stored; the programmer only has to remember the name. A name used in this way to refer to data stored
in memory is called a variable.
In Java, the only way to get data into a variable that is into the box that the variable names are with an
assignment statement. An assignment statement takes the form:
Local Variables
Local variables are variables that used within a block of codes. Similar to how an object stores its
state in fields, a method will often store its temporary state in local variables. The syntax for
declaring a local variable is similar to declaring a field (Ex, int count = 0 ;). There is no special
keyword designating a variable as local; that determination comes entirely from the location in
which the variable is declared, which is between the opening and closing braces of a method. As
such, local variables are only visible to the methods in which they are declared; they are not
accessible from the rest of the class.
A variable in Java is designed to hold only one particular type of data; it can legally hold that type of data
and no other. The compiler will consider it to be a syntax error if you try to violate this rule. We say that
Java is a strongly typed language because it enforces this rule.
Every programming language has its own set of rules and conventions for the kinds of names that you're
allowed to use, and the Java programming language is no different. The rules and conventions for naming
your variables can be summarized as follows:
A variable can be used in a program only if it has first been declared. A variable declaration statement is
used to declare one or more variables and to give them names. When the computer executes a variable
declaration, it sets aside memory for the variable and associates the variable's name with that memory. A
simple variable declaration takes the form:
datatype-name variable-name;
The variable-name-or-names can be a single variable name or a list of variable names separated by
commas. (We'll see later that variable declaration statements can actually be somewhat more complicated
than this.) Good programming style is to declare only one variable in a declaration statement, unless the
variables are closely related in some way. For example:
int numberOfStudents;
It is also good style to include a comment with each variable declaration to explain its purpose in the
program, or to give other information that might be useful to a human reader. For example:
Doing so tells your program that a field named "product” and “sum” exist and hold numerical data, and
have an initial value of "1" and “0” respectively. A variable's data type determines the values it may
contain, plus the operations that may be performed on it. In addition to int, the Java programming
language supports seven other primitive data types. A primitive type is predefined by the language and is
named by a reserved keyword. Primitive values do not share state with other primitive values. The eight
primitive data types supported by the Java programming language are:
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value
of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving
memory in large arrays, where the memory savings actually matters.
short: The short data type is a 16-bit signed two's complement integer. It has a minimum
value of -32,768 and a maximum value of 32,767 (inclusive). As with int, the same guidelines
apply: you can use a short to save memory in large arrays, in situations where the memory
savings actually matters.
int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this
data type is generally the default choice unless there is a reason (like the above) to choose
long: The long data type is a 64-bit signed two's complement integer. It has a minimum
value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807
(inclusive). Use this data type when you need a range of values wider than those provided
by int.
float: The float data type is a single-precision 32-bit floating point. As with the
recommendations for byte and short, use a float (instead of double) if you need to save
memory in large arrays of floating point.
double: The double data type is a double-precision 64-bit floating point. For decimal
values, this data type is generally the default choice.
boolean: The boolean data type has only two possible values: true and false. Use this data
type for simple flags that track true/false conditions. This data type represents one bit (1 or
0) of information, but its "size" isn't something that's precisely defined.
In addition to the eight primitive data types listed above, the Java programming language also provides
special support for character strings via the java.lang.String class. Enclosing your character string within
double quotes will automatically create a new String object.
The Java programming language also supports a few special escape sequences for char and String literals:
\b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single
quote), and \\ (backslash).
There's also a special null literal that can be used as a value for any reference type. null may be assigned to
any variable, except variables of primitive types. There's little you can do with a null value beyond testing
for its presence. Therefore, null is often used in programs as a marker to indicate that some object is
unavailable.
The following statement allocates enough memory for arrayOfInts to contain ten integer elements.
In general, when creating an array, you use the new operator, plus the data type of the array elements, plus
the number of elements desired enclosed within square brackets ('[' and ']').
Now that some memory has been allocated for your array, you can assign values to its elements and
retrieve those values:
Finally, you can use the built-in length property to determine the size of any array. The code
Each item in an array is called an element, and each element is accessed by its numerical index.
Numbering /indexing begin with 0.
The next few lines assign values to each element of the array:
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
Here the length of the array is determined by the number of values provided between { and }.
You can also declare an array of arrays (also known as a multidimensional array) by using two or more
sets of square brackets, such as String[][] names. Here String is the data type and names is the name of
multidirectional arrays. Each element, therefore, must be accessed by a corresponding number of index
values.
In the Java programming language, a multidimensional array is simply an array whose components are
themselves arrays. A consequence of this is that the rows are allowed to vary in length, as shown in the
following MultiDimArrayDemo program:
class MultiDimArrayDemo {
{"Smith", "Jones"}};
Control Statements
The control statements are used to control the flow of execution of the program. This execution order
depends on the supplied data values and the conditional logic. Java contains the following types of control
statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements like break, continue, return (Read from books / internet)
Selection statements:
1. If Statement
This is a control statement to execute a single statement or a block of code, when the given condition is
true and if it is false then it skips if block and rest code of program is executed.
Syntax:
if(conditional_expression){
<statements>; …..
}
2. If-else Statement
The "if-else" statement is an extension of if statement that provides another option when 'if' statement
evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not
equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2 = = 0){
System.out.println("This is even number");
}
else{
System.out.println("This is not even number"); }
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of
90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
Object Oriented Programming in Java Page 16
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}}
You may have noticed that the value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are
executed (grade = 'C';) and the remaining conditions are not evaluated.
3. Switch Statement
This is an easier implementation to the if-else statements. The keyword "switch" is followed by an
expression that should evaluates to byte, short, char or int primitive data types, only. In a switch block
there can be one or more labeled cases. The expression that creates labels for the case must be unique.
The switch expression is matched with each case label. Only the matched case is executed, if no case
matches then the default statement (if present) is executed.
Syntax:
switch(control_expression){
case expression 1:
<statement>;
case expression 2:
<statement>;
...
...
case expression n:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid
entry");
break;
You could also display the name of the month with if-then-else statements:
Deciding whether to use if-then-else statements or a switch statement is based on readability and the
expression that the statement is testing. An if-then-else statement can test expressions based on ranges of
values or conditions, whereas switch statement tests expressions based only on a single integer,
enumerated value, or String object.
Repetition Statements:
1. While loop statements:
This is a looping or repeating statement. It executes a block of code or statements till the given conditions
are true. The expression must be evaluated to a boolean value. It continues testing the condition and
executes the block of code. When the expression results to false control comes out of loop.
Syntax:
while(expression){
<statement>;
...;
...;
}
Example: Here expression i<=10 is the condition which is checked before entering into the loop
statements. When i is greater than value 10 control comes out of loop and next statement is executed. So
here i contains value "1" which is less than number "10" so control goes inside of the loop and prints
current value of i and increments value of i. Now again control comes back to the loop and condition is
checked. This procedure continues until i becomes greater than value "10". So this loop prints values 1 to
10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10){
System.out.println("Num " + i);
i++; }
The while statement evaluates expression, which must return a boolean value. If the expression evaluates
to true, the while statement executes the statement(s) in the while block. The while statement continues
testing the expression and executing its block until the expression evaluates to false. Using the while
statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo
program:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the
loop instead of the top. Therefore, the statements within the do block are always executed at least once, as
shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}}
3. The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it
as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.
The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
When using this version of for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for
this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of for statement to print the numbers 1 through
10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
} }}
The scope of this variable extends from its declaration to the end of the block governed by the for
statement, so it can be used in the termination and increment expressions as well. If the variable that
controls for statement is not needed outside of the loop, it's best to declare the variable in the initialization
expression. The names i, j, and k are often used to control for loops; declaring them within the
initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows: