1 13 Merged
1 13 Merged
Consultation Hour
By appointment through mail
Introduction to Object Oriented
Programming
Objects
Encapsulation
Inheritance
Polymorphism
or a remote control).
We can still understand the concept of a television,
A class should:
Provide a well-defined interface - such as the remote control of
the television.
Represent a clear concept - such as the concept of a television.
television.
Methods (or behavior) - are the ways in which the object can
Unified Modelling
Language (UML)
representation of
the Television class for
object-oriented modelling
and programming.
Encapsulation is used to hide the mechanics of the object, allowing the actual
implementation of the object to be hidden. All we need to understand is the interface that
is provided for us.
For example, Television class, where the functionality of the television is hidden from
us, but we are provided with a remote control, or set of controls for interacting with
the television, providing a high level of abstraction.
There is no requirement to understand how the signal is decoded from the aerial and
converted into a picture to be displayed on the screen before you can use the television.
10
There is a sub-set of functionality that the user is allowed to call, termed the
interface.
What are the interfaces of a Car?
The full implementation of a class is the sum of the public interface plus the
private implementation.
Encapsulation is the term used to describe the way that the interface is
separated from the implementation.
Encapsulation as data-hiding
Allow certain parts of an object to be visible
Advantages for both the user and the programmer
User
Need only understand the interface.
Need not understand how the implementation works or was
created.
Programmer
Can change the implementation, but need not notify the user. 11
12
more accurately
webbed feet.
13
14
One way to determine that you have organized your classes correctly is
to check them using the "IS-A" and "IS-A-PART-OF" relationship
checks.
It is easy to confuse objects within a class and children of classes when
you first begin programming with an OOP methodology.
15
16
When a class inherits from another class it inherits both the states and
methods of that class, so in the case of the Car class inheriting from the
Vehicle class the Car class inherits the methods of the Vehicle class
engineStart(), gearChange(), lightsOn() etc.
The Car class will also inherit the states of the Vehicle class
isEngineOn, isLightsOn, numberWheels etc.
Over-loading
17
18
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
5
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
8
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
10
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java implements several security
Java Is Secure
mechanisms to protect your system against
• Java Is Architecture-Neutral harm caused by stray programs.
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic 11
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure Write once, run anywhere
• Java Is Architecture-Neutral With a Java Virtual Machine (JVM),
• Java Is Portable you can write one program that will
run on any platform.
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
12
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Because Java is architecture neutral,
Java Is Portable
Java programs are portable. They can
• Java's Performance be run on any platform without being
• Java Is Multithreaded recompiled.
• Java Is Dynamic
13
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
14
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Multithread programming is smoothly
• integrated in Java, whereas in other
Java's Performance
languages you have to call procedures
• Java Is Multithreaded specific to the operating system to enable
• Java Is Dynamic multithreading.
15
• NetBeans
• Eclipse
• IntelliJ IDEA
19
20
21
22
Creating, Compiling,
and Running Programs
23
Compiling Java Source Code
24
25
Execute statement
26
27
• Class name
• Main method
• Statements
• Statement terminator
• Reserved words
• Comments
• Blocks
28
34
" " Opening and closing Enclosing a string (i.e., sequence of characters).
quotation marks
; Semicolon Marks the end of a statement.
35
36
37
38
39
40
• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing Lines
• Block Styles
41
42
43
• Spacing
– Use blank line to separate segments of the code.
44
End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
45
• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result
46
47
48
49
Object-Oriented Programming
Language Basics
Variables
Primitive Data Types
Operators
Assignment, Arithmetic, and Unary Operators
Equality, Relational, and Conditional Operators
Bitwise and Bit Shift Operators
Expressions, Statements, and Blocks
Control Flow Statements
if – then and if – then – else
switch
while and do – while
for and branching statements
In the Java programming language, the terms "field" and "variable" are both used; this is a
common source of confusion among new developers, since both often seem to refer to the
same thing.
Class Variables (Static Fields) - A class variable is any field declared with
the static modifier; this tells the compiler that there is exactly one copy of this
variable in existence, regardless of how many times the class has been
instantiated. A field defining the number of gears for a particular kind of
bicycle could be marked as static since conceptually the same number of gears
will apply to all instances. The code static int numGears = 6; would create
such a static field. Additionally, the keyword final could be added to indicate
that the number of gears will never change.
Local Variables - a method will often store its temporary state in local
variables. 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.
• For more than one word, capitalize the first letter of each subsequent word.
Example: gearRatio, numberOfGears, monthlySalary etc
• Capitalize every letter and separate subsequent words with the underscore
character for variables that are made to store constant value, such that
those with modifiers static, final, and static final both.
Example: static final NUM_GEARS = 6;
8
BITS Pilani, Pilani Campus
Primitive Data Types (Contd.)
• It's not always necessary to assign a value when a field is declared. Fields that are
declared but not initialized will be set to a reasonable default by the compiler.
Generally speaking, this default will be zero or null, depending on the data type.
Relying on such default values, however, is generally considered bad programming
style.
Operators Precedence
postfix expr++ expr–
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
Operators with higher precedence are evaluated before
bitwise AND & operators with relatively lower precedence. Operators on the
bitwise exclusive OR ^ same line have equal precedence. When operators of equal
precedence appear in the same expression, a rule must govern
bitwise inclusive OR |
which is evaluated first. All binary operators except for the
logical AND && assignment operators are evaluated from left to right; assignment
logical OR || operators are evaluated right to left.
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
14
BITS Pilani, Pilani Campus
Integer and Floating point division
15
BITS Pilani, Pilani Campus
Type Casting
• A type cast takes a value of one type and produces a value of another
type with an "equivalent" value
– If n and m are integers to be divided, and the fractional portion of the
result must be preserved, at least one of the two must be type cast to
a floating-point type before the division operation is performed
double ans = n / (double)m;
– Note that the desired type is placed inside parentheses immediately in
front of the variable to be cast
– Note also that the type and value of the variable to be cast does not
change
16
BITS Pilani, Pilani Campus
More on Type Casting
17
BITS Pilani, Pilani Campus
Questions
Visibility modifier
Keyword class Name of the class
(More on this later)
} NO semi-colon
}
BITS Pilani, Pilani Campus
Defining Methods
public float calculateSimpleInterest(
float pri, float rate, float time){
return((pri*rate*time)/100));
}
• Overloaded methods are differentiated by the number and the type of the
arguments passed into the method
• You cannot declare more than one method with the same name and the
same number and type of arguments, because the compiler cannot tell
them apart.
• The compiler does not consider return type when differentiating methods,
so you cannot declare two methods with the same signature even if they
have a different return type.
public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}
• You don't have to provide any constructors for your class, but you must be
careful when doing this. The compiler automatically provides a no-argument,
default constructor for any class without constructors.
• You can use access modifiers in a constructor's declaration to control which other
classes can call the constructor.
• You can use any data type for a parameter of a method or a constructor.
This includes primitive data types, such as doubles, floats, and integers, as
you saw in the computePayment method, and reference data types, such as
objects and arrays.
• This method that accepts three Point objects as argument. The method
creates a new Triangle object and initializes it from three Point objects
(assume that Point is a class that represents an x, y coordinate)
}
The Java programming language doesn't let you pass
methods into methods. But you can pass an object into
a method and then invoke the object's methods.
BITS Pilani, Pilani Campus
Parameter Names
• When you declare a parameter to a method or a constructor, you
provide a name for that parameter. This name is used within the
method body to refer to the passed-in argument.
• A parameter can have the same name as one of the class's fields. If
this is the case, the parameter is said to shadow the field.
Shadowing fields can make your code difficult to read and is
conventionally used only within constructors and methods that set a
particular field.
• The Circle class has three fields: x, y, and radius. The setOrigin
method has two parameters, each of which has the same name as
one of the fields. Each method parameter shadows the field that
shares its name. So using the simple names x or y within the body
of the method refers to the parameter, not to the field. To access
the field, you must use a qualified name.
int x = 3;
passMethod(x);
S.o.p("After invoking passMethod, x = " + x);
}
private int i;
public A(){
i = 5;
}
/* Overloaded constructors are used to
public A(int x){ instantiate and initialize the fields
i = x; with the values supplied via the
} constructor */
Note: Because Strings are very common, using new when creating String objects is optional.
The statement String s1, s2; creates two local variables on the stack.
The statements
s1 = new String( “abc” );
s2 = “abc”;
s1
s2 abc abc
Recall that s1 and s2 contain the addresses of their respective String objects.
Since the String objects have different addresses on the heap, s1 == s2 is
false. The == operator determines if two reference variables refer to the same
Object.
Stack Heap
On the other hand, consider this code
and corresponding picture of
memory s1
String s1 = “abc”; s2 abc
String s2 = s1; s1 and s2 are ALIASed
Now s1 and s2 refer to the same String object. This is known as ALIASING, is often
unintentional, and can be dangerous.
Java has a built-in “garbage collector”. From time to time Java detects
objects has been “orphaned” because no reference variable refers to
them. The garbage collector automatically returns the memory for
those objects to the free heap.
main
JVM Memory usage
name null
salary null
sales null
bonus null
String instance
“John”
Employee:new
Integer instance
this
name 5000
salary
sales
Integer instance
main 5
JVM Memory usage
name null
salary null
sales null
bonus null
String instance
“John”
Employee:new
Integer instance
this
name 5000
salary
sales
Integer instance
main 5
JVM Memory usage
name
salary null
sales null
bonus null
String instance
“John”
Employee:new
Integer instance
this
name 5000
salary
sales
Integer instance
main 5
JVM Memory usage
name
salary
sales null
bonus null
String instance
“John”
Employee:new
Integer instance
this
name 5000
salary
sales
Integer instance
main 5
JVM Memory usage
name
salary
sales
bonus null
String instance
“John”
Employee:new
Integer instance
main
5
JVM Memory usage
name
salary
sales
bonus null
String instance
“John”
Employee:new
Integer instance
main
5
JVM Memory usage
name
salary
sales
bonus null
String instance
“John”
Integer instance
5000
main
john Integer instance
5
JVM Memory usage
name
salary
sales
bonus null
String instance
findEmployeeBonus “John”
salary 5000
noOfSales 5
Integer instance
5000
main
john Integer instance
5
JVM Memory usage
name
salary
sales
getBonusPercentage
bonus null
salary 5000
String instance
findEmployeeBonus “John”
salary 5000
noOfSales 5
Integer instance
5000
main
john Integer instance
5
JVM Memory usage
name
salary
sales
getBonusPercentage
bonus null
salary 5000
percentage 500
String instance
findEmployeeBonus “John”
salary 5000
noOfSales 5
Integer instance
5000
main
john Integer instance
5
JVM Memory usage
name
salary
getBonusPercentage
sales
salary 5000 bonus null
percentage 500
return 500
String instance
findEmployeeBonus “John”
salary 5000
noOfSales 5
Integer instance
5000
main
john Integer instance
5
JVM Memory usage
name
salary
sales
bonus null
findEmployeeBonus
String instance
salary 5000
“John”
noOfSales 5
bonusPercentage 500
bonus 2500
Integer instance
5000
main
john Integer instance
5
JVM Memory usage
name
salary
sales
bonus null
findEmployeeBonus
String instance
salary 5000
“John”
noOfSales 5
bonusPercentage 500
bonus 2500
return 2500 Integer instance
5000
main
john Integer instance
5
JVM Memory usage
name
salary
sales
bonus
String instance
“John”
Integer instance
5000
Integer instance
2500
JVM Memory usage
name
salary
sales
bonus
String instance
“John”
Integer instance
5000
Integer instance
2500
JVM Memory usage
name
salary
sales
bonus
String instance
“John”
Integer instance
5000
Integer instance
Integer instance
2500
BITS Pilani
Pilani Campus
Parent
Inherited
capability
Child
2
BITS Pilani, Pilani Campus
Final Members: A way for Preventing
Overriding of Members in Subclasses
• All methods and variables can be overridden by
default in subclasses.
• This can be prevented by declaring them as final
using the keyword “final” as a modifier. For example:
– final int marks = 100;
– final void display();
• This ensures that functionality defined in this method
cannot be altered any. Similarly, the value of a final
variable cannot be altered.
3
BITS Pilani, Pilani Campus
Final Classes: A way for Preventing Classes
being extended
4
BITS Pilani, Pilani Campus
Abstract Classes
5
BITS Pilani, Pilani Campus
Abstract Class Syntax
6
BITS Pilani, Pilani Campus
Abstract Class -Example
Shape
Circle Rectangle
7
BITS Pilani, Pilani Campus
The Shape Abstract Class
8
BITS Pilani, Pilani Campus
Abstract Classes
10
BITS Pilani, Pilani Campus
Summary
11
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Arrays
Introduction to Arrays
• An array is a data structure used to process a
collection of data that is all of the same type
– An array behaves like a numbered list of variables
with a uniform naming mechanism
– It has a part that does not change:
• the name of the array
– It has a part that can change:
• an integer in square brackets
– For example, given five scores:
score[0],score[1],score[2],score[3],score[4
]
• The declaration
double[] score = new double[5];
results in the 5 elements
score[0], score[1], score[2], score[3], score[4]
(continued)
(continued)
(continued)
(continued)
BITS Pilani, Pilani Campus
Array Parameters
• Arrays of double may be defined as follows:
double[] a = new double[10];
double[] b = new double[30];
• Given the arrays above, the method doubleElements
from class SampleClass can be invoked as follows:
SampleClass.doubleElements(a);
SampleClass.doubleElements(b);
– Note that no square brackets are used when an entire
array is given as an argument
– Note also that a method that specifies an array for a
parameter can take an array of any length as an argument
(continued)
– Note that the above code will not make b an exact copy
of a, unless a and b have the same length
(continued)
(continued)
Searches the specified array of type for the specified value using the binary
search algorithm.
Returns true if the two specified arrays of type are equal to one another.
Assigns the specified type value to each element of the specified array of
type.
Assigns the specified type value to each element of the specified range of the
specified array of types.
Sorts the specified range of the specified array of type into ascending
numerical order.
word “java"
“Java"
• result += word3;
//concatenates word3 to result “rethinking”
0 2 6 10 15
boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2
boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2, case-
blind
b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true
if(team.equalsIgnoreCase(“raiders”))
System.out.println(“Go You “ + team);
//negative differences
diff = “apple”.compareTo(“berry”);//a before b
diff = “Zebra”.compareTo(“apple”);//Z before a
diff = “dig”.compareTo(“dug”);//i before u
diff = “dig”.compareTo(“digs”);//dig is shorter
//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal
//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
BITS Pilani, Pilani Campus
Methods — trim
word1 = word1.toUpperCase();
• A common bug:
word1
word1.toUpperCase();
remains
unchanged
To extract data that is at a “higher level” than the byte, we must “encase” the
InputStream, System.in, inside an InputStreamReader object that converts
byte data into 16-bit character values (returned as an int).
BufferedReader
InputStreamReader
import java.io.*;
public class TotalNumbers throws java.io.IOException{
private String str;
private int num;
public static void main (String [] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print(“Enter four integers: “);
str = br.readLine( );
str = 6 2 4 3 2 1
str = 6 2 4 3 2 1
Unlike primitive types, objects have operations called methods that they can
be directed to perform. (These methods have visibility static they can be
accessed by using the class name without instantiating objects of the class.
Wrapper class objects have a method for converting a string into a primitive
type, and a method for transforming a primitive type into a string.
wrapper method name return type
Integer parseInt(String st) int
Integer toString(int num) String
Double parseDouble(String st) double
Double toString(double num) String
Float parseFloat(String st) float
Long parseLong(String st) long
Return to the code for extracting tokens from the input string
Step 3 – Form input stream of characters into a string (look for eol)
BufferedReader br = new BufferedReader(isr);
String str = br.readLine( ); Need to throw java.io.IOException in function in
which it is used
String s1 = st.nextToken( );
//note can use while(st.hasMoreTokens( )) to repeatedly extract each
//token in the string
Step 6 – Use wrapper class methods to convert token (string) to primitive type
the message
?
OK Cancel
WARNING_MESSAGE !
QUESTION_MESSAGE ?
INFORMATION_MESSAGE
ERROR_MESSAGE
PLAIN_MESSAGE
produces
greetings X
Little Programmers!
OK
JOptionPane.PLAIN_MESSAGE
The icon_type determines which of the five icons (the fifth being no
icon at all) will appear in the dialog box.
1. import javax.swing.*;
2. Use an input dialog box to prompt the user to enter data (returns a String)
String inString = JOptionPane.showInputDialog(“your message”);
3. Use a StringTokenizer (if necessary) to extract the individual tokens
from the input String
4. Convert (String) tokens into primitive types wherever necessary using
the appropriate wrapper class.
5. Use a dialog box to display the output
JOptionPane.showMessageDialog(null,”message”, “title”, icon-type):
6. When using a Message dialog box, end the program with
System.exit(0);
<<Interface>>
Speaker
speak()
class Student{
private String name;
private String idNo;
private int age; StudentByName StudentByIdNo StudentByAge
// Sort By Name
Comparator c1 = new StudentByName();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);