Lecture4_1 - Illinois Institute of Technology

Download Report

Transcript Lecture4_1 - Illinois Institute of Technology

CS 115
OBJECT ORIENTED PROGRAMMING I
LECTURE 4_1
GEORGE KOUTSOGIANNAKIS
Copyright: 2015 Illinois Institute of TechnologyGeorge Koutsogiannakis
1
Previous Lecture Topics
•
•
•
•
•
•
•
Data Types.
Variables.
Constants.
Type casting of Data Types.
Expressions.
Arithmetic Operators.
Precedence of Operators.
2
Lecture 4 Topics
•
•
•
•
•
•
•
Mixed Type Arithmetic
Typecasting-Implicit/Explicit
Structure of a Java program
Classes – What is a class?
What is an object of a class?
How do we create objects of a class?
Constructors
3
Arithmetic Operators
• In Programming arithmetic expressions we use the following
symbols. Each symbol is called an arithmetic operator:
– / forward slash is used for division i.e 4/3
– * asterisk is used for multiplication
– +, - used for addition and subtraction. Notice that the + operator is
also used a symbol with a different meaning sometimes (this is called
operator overloading).
– % modulus operator. Gives the remainder of a division.
– ( , ) opening and closing parentheses.
4
Review of Precedence of Operators
• Suppose we have the expression:
3*4/2+(6-3*2/2-1*(2+3-2*5/2))
What is the result?
How does the system (java run time system in the computer) calculate
the result?
Answer:
– First anything within a parenthesis gets calculated, starting with the innermost
parethensis. Parentheses are given priority. Each parenthesis is calculated by
itself. Within a parenthesis the precedence of operators is followed i.e.
multiplication and division first then addition and subtraction:
2+3-2*5/2
• multiplication and division have equal precedence and they get applied
before + or –
• therefore we apply the leftmost of the equal precedence operators first.
5
Review of Precedence of Operators
• 2*5=10 first , then 10/2=5
• Next we apply the + and then the - (+, - are of equal precedence but + comes first
because it is the leftmost of the two in the expression).
• 2+3-5=0 (result of inner most parenthesis).
– Now let us calculate the next parenthesis (6-3*2/2-1*0)
• Again multiplication is first ( multiplication and division come before addition and
subtraction) starting left to right and covering all operators of equal precedence.
6-6/2-1*0
Next the division
6-3-1*0
Next the last multiplication
6-3-0= 3
– Now the remainder of the expression
3*4/2+3 First the multiplication 3*4=12 then 12/2=6 and finally the subtraction
FINAL RESULT: 6+3=9
6
Modulus Operator
When two integers are divided:
– the quotient is an integer data type
– any fractional part is truncated (discarded)
• To get the remainder, use the modulus
operator with the same operands: %
i.e 10%3=1 because the remainder of the division is 1
7
Division by Zero
• Integer division by 0:
Example: int result = 4 / 0;
At run time, the Java Runtime System generates an ArithmeticException and
the program stops executing. Division by zero is not allowed.
• Floating-point division by 0:
– If the dividend is not 0 as an integer, then the result is Infinity --i.e.
4.3/0.0=infinity.
– If the dividend and divisor are both 0, the result is NaN (not a
number) ---i.e. 0/0=NaN
8
Operands
• Consider the following Expression:
2+3-5
– An operator operates on Operands
– + , –, *, / operators require 2 operands each.
– + operator has the Operands 2 and 3 in our
example.
9
Mixed-Type Arithmetic– Conversions of
Data Types
• There is a concern with data types when the operands of an operator are
not of the same data type.
i.e.
2 * 2.3
WHERE SHOULD THE SYSTEM STORE THE RESULT IN MEMORY? As an int
memory space (4 bytes) or as a double memory space (8 bytes)?
• Even if the data types of the operands are the same we could still have an
issue as to the data type of the result
i.e.
3/2
• Therefore rules are needed in the programming language (Java in this
case) to handle the results of this type of operations.
10
Mixed-Type Arithmetic– Conversions
of Data Types
Implicit Type Casting
• By “Implicit Type Casting” we mean that the Java Runtime
System changes a particular data type implicitly: in other
words the programmer did NOT program the change to the
data type with an explicit programming instruction.
• PROMOTION RULE
– When performing calculations with operands of different
data types in an expression:
• Lower-precision operands are promoted automatically
(implicitly) to higher-precision data types, then the
operation is performed. That conversion of the data
type is called Numeric Promotion.
11
Mixed-Type Arithmetic– Conversions of
Data Types
Implicit Type Casting
– Promotion is effective only for expression
evaluation; not a permanent change. In other
words the operand after the calculation returns to
its original data type.
– This is called implicit type casting because it is
done by the syatem and not by the programmer.
• For example: any expression involving a floatingpoint operand will have a floating-point result.
12
Promotion
• Therefore the term numeric promotion refers to
changing a data type variable (which has already
been declared) in an expression from a lower
precision to higher precision at compile time (in
other words the compiler automatically adjusts the
data types).
– Promotion takes place, for instance, when we have an
arithmetic expression to be evaluated like the one below:
Operand1 Operator Operand2
3
+
4.2
(as an example)
13
Promotion
– Thus, the first operand will be promoted (remember the promotion is
temporary) so that we now have:
3.0 + 4.2
After the expression is calculated 3.0 returns to its original value 3
(an int data type)
14
Promotion
– Another example:
int x=3;
double y=4.0;
double z=0;
z= x+y;
In this case the variable x is temporarily promoted to a double (only
for the duration of the calculation of the expression by the program).
The result is a double which is saved in identifier z.
Notice that after the expression is calculated the identifier x remains
an int holding the value 3 (not 3.0).
• Question: explain the meaning of the phrase “the variable x is
temporarily promoted to a double “ in terms of memory spaces in the
computer.
15
Rules of Promotion
The compiler applies the first of these rules that fits:
1. If either operand is a double, the other operand is
converted to a double.
2. If either operand is a float, the other operand is converted
to a float.
3. If either operand is a long, the other operand is converted
to a long.
4. If either operand is an int, the other operand is promoted to
an int
5. If neither operand is a double, float, long, or an int, both
operands are promoted to int.
16
Assignment Conversion
•
The equal sign = is not called equal in programming languages. It is
instead called the assignment operator.
• It is used to indicate that one variable’s value (one identifier’s value) is
transferred from its memory space to the other variables memory space
i.e
int c= 2/3+(3*25%2) means:
calculate the expression and then assign its result (store the result) in the
memory space identified by the symbol c if type int (4 byte sreserved)
i.e
int d =5;
int c=d
In this case we want the value stored in the identifier d (memory spaced of
4 bytes) to ALSO be stored (assigned) in the memory space identified as c
(also 4 bytes)
17
Assignment Conversion
• Assignment conversion takes place when we are trying to assign one
particular data type identifier to another data type identifier.
– For example
–
int x=3;
–
double y=0;
–
y=x;
•
In other words take the value of x and assign it to the identifier y
• or another way of saying the same thing is:
–
Take the contents of memory location identified by x and place it in the memory
location identified by y.
• The above is valid conversion because a lower precision can be assigned to a higher
precision identifier (the inverse is not true).
– Remember that y is 8 bytes and x is 4 bytes. We can take 4 bytes of data and put it in a
memory space of 8 bytes but not the other way around.
18
Example Of Implicit Type casting
public class TestPromotion
{
public static void main(String[] args)
{
double taxRate=0.5345;
float salesTax=0.5f;
//demotion is allowed. Therefore the following is allowed
//where taxRate accepts a float;
taxRate=salesTax;
//The following is not allowed. Compiler will produce a warning
//Possible loss of precision message Identifier salesTax can not be promoted to a double
salesTax=0.9f;
salesTax=taxRate;
}
}
19
Example Of Implicit Type casting
• In this example salesTax represents a float (which
takes 4 bytes of memory) and taxRate a double
(which takes 8 bytes of memory).
• It is O.K. to try to store a float into a memory area
greater than the float memory area.
• It is NOT O.K. to try to store a double (8 bytes) into
a memory area less that 8 bytes ( a float has 4
bytes).
20
Another Example of Implicit Type
Casting
public class TestPromotion1
{
public static void main(String[] args)
{
double taxRate=0.5345;
float salesTax=0.5f;
double result=taxRate+salesTax;
System.out.println(“Thre result is”+result);
}
}
• Here float data type salesTax is implicitly type casted to a double temporarily so that the
expression taxRate+salesTaxc an be evaluated.
• Output:
• The result is:1.0345
21
Another Example of Implicit Type
Casting
public class TestPromotion1
{
public static void main(String[] args)
{
double taxRate=0.5345;
int salesTax=2;
double result=taxRate+salesTax;
System.out.println(“Thre result is”+result);
}
}
Output:
The result is:2.5345
The int data type salesTax was implicitly (without us asking for it via an instruction) type casted
to a double in order to be added with the double data type taxRate.
22
Type Casting -Explicit
• The programmer can write a programming instruction to
explicitly ask that a data type be converted to a different data
type. This is called explicit type casting.
• Explicit type casting is done by enclosing the new data type
name in parenthesis in front of the data type that w eare
changing i.e.
– int a=(int)4.324;
Or
double d=4.324;
int a=(int)d;
23
Structure of a Java program
public class NameOfClass
{
//instance variables or attributes of the class are declared here
int a=0;
char c=‘v’;
double anotherd=3.64;
// next the methods of the class
public void firstMethod( )
{
//code for this method
}
public int secondMethod()
{
//code for second method
}
} //end of class
24
Class-what is a class
• A class is a category.
– i.e Student is a class. It represents a category of
people that share common characteristics
– We call those common characteristics: attributes
• For example, every student has:
– A first name.
– A last name
– A student Id
– Is registered at a school
– Takes certain courses etc.
– Those are some of the attributes that we can come up. There are
other of course that we can add to the list.
25
Class-what is a class
• In Java we create classes as they are needed.
That is why we start a Java program by
declaring a class name:
• i.e public class Student
{
//we declare the attributes
// we write methods for the class
}
26
Class-what is a class
• The attributes make up the data of the class
• The methods manipulate the data.
• Suppose someone says: “The student earns grades”. Come up with the
data and the methods for a class.
• The noun in the sentence is the class name, the verb is a method. The
attribute is: grade.
•
i.e public class Student
{
char grade=‘ ‘;
public void setGrade(char agrade)
{
grade=agrade;
}
}
27
Object-Oriented Programming
• Classes combine data and the methods (code) to manipulate the data
• Classes are a template used to create specific objects.
– An object is a specific instance of a class
– i.e In the class Student we may have a specific student (an object of class Student) with
specific values for the attributes that we gave to the class:
•
•
•
•
First Name is John
Last Name is Doe
Grade is A
Etc.
• All Java programs consist of at least one class.
• Object Oriented Programming (OOP) refers to the usage of classes in our
programs.
28
Why Use Classes?
•
•
•
•
Usually, the data for a program is not simply one item.
Often we need to manage entities like students, books, flights, etc.
We need to be able to manipulate such entities as a unit.
Classes allow us to separate the data for each object, while using common
code to manipulate each object.
• Student class
– Data: name, year, and grade point average
– Methods: store/get the value of the data, promote to next year, etc.
• Student object
Object name: student1
Data: Maria Gonzales, Sophomore, 3.5
29
Class Members
• Members of a class
– the class's fields and methods. Fields is another name for attributes.
• Fields
– instance variables and static variables (we'll define static later)
– Instance variables
• variables defined in the class and given a value in each object
fields can be:
– any primitive data type (int, double, etc.)
– objects of the same or another class
• Methods
– the code to manipulate the object data
30
Encapsulation
• Instance variables are usually declared to be private, which
means that they cannot be accessed directly outside the class.
• Users (clients) of the class must reference the private data of
an object by calling methods of the class.
• Thus the methods provide a protective shell around the data.
We call this encapsulation.
• Benefit: the class’ methods can ensure that the object data is
always valid
31
Objects
• Object reference
– an identifier of the object
• Instantiating an object
– creating an object of a class; assigns initial values
to the object data
– Objects need to be instantiated before being used
• Instance of the class
– an object after instantiation
32
Naming Conventions
• Class names: start with a capital letter
• Object references: start with a lowercase
letter
• In both cases, internal words start with a
capital letter
• Example: class: Student, PetAnimal
objects: marcusAustin,
myBoaConstrictor
33
Example of a Class
public class Student
{
//let us declare 4 attributes (fields) and initialize them
String firstName=“ “;
String lastName=“ “;
int studentID=0;
double gradeAverage=0.0;
// next we create a method called the constructor method.
public Student(String fn, String ln, int id, double gradaver)
{
firstName=fn;
lastName=ln;
studentID=id;
gradeAverage=gradaver;
}
// The constructor initializes the attributes (or some of the attributes) to specific values requested by a
user. The constructor in the above example is called a non default constructor. We will show later
another type of constructor method called default constuctor.
34
Example of a Class
public String getFirstName()
{
return firstName;
}
//The above method is called an Accessor method because it accesses the value of an
attribute
public void setfirstName(String finam)
{
firstName=finam;
}
//The above method is called a Mutator method because it can change the value of
an attribute.
35
Example of a Class
• The previous class is called a template class. It
is a template of Student category (class).
• Notice that it ha sno main method although it
has other methods such as
– Constructor methods
– Accessor methods
– Mutator methods
• Another Java program called the client
program can utilize this class.
36
Reusability of Classes
• Reuse
– class code is already written and tested
– you build a new application faster
– the application will be more reliable
Example: A Date class could be used in a
calendar program, appointment-scheduling
program, online shopping program, etc
37
How to Reuse a Class
• You don't need to know how the class is
written or see the code of the class
• You do need to know the application
programming interface (API) of the class
• The API is published and tells you:
– how to create objects
– what methods are available
– how to call the methods
38
API
• Documentation of the Java API is available on
the Internet by going to site:
http://java.sun.com/javase/6/docs/api
39
Client Class
• Suppose we have written the program for the
class Student.
• Another class, let us call it: StudentClient,
needs to use the student class.
public class StudentClient
{
// This class is going to have a main method
// inside the main method we are going to create a Student class object (the term is: instantiate a
student class object
// The student object will allow us to manipulate the data of the class (the values of the attributes) by
using the accessor and mutator methods of the template class Student.
}
40
Back to Student Template Class
public class Student
{
//let us declare 2 attributes (fields) and initialize them
String lastName=“ “;
int studentID=0;
// next we create a method called the default constructor method.
public Student()
{
lastName=Joe;
studentID=10;
}
public Student(String ln, int id)
{
lastName=ln;
studentID=id;
}
41
Back to Student Template Class
public String getLastName()
{
return lastName;
}
public void setLastName(String ln)
{
lastName=ln;
}
public int getStudentID()
{
return studentID;
}
public void setStudentID()
{
return studentID;
}
THERE ARE TWO ERRORS IN THE LAST METHOD!! IDENTIFY THE ERRORS.
42
Constructors
• Initialize the fields (attributes)
• A class can have a number of different
constructors.
• Two types:
– Default constructor takes no arguments. Initializes
the fields to specific values.
– Non Default constructor takes arguments.
Initializes the fields to what values the arguments
have.
43
Constructors
• Notice that constructors MUST HAVE THE
SAME NAME AS THE CLASS
• Notice that constructors do not return any
data type, NOT EVEN VOID.
44
Study Guide
• Chapter 2
– All of section 2.4
• Chapter 3
– 3.1, 3.2
45