0% found this document useful (0 votes)
7 views47 pages

Lecture 2

The document provides an overview of Object-Oriented Programming concepts, focusing on classes, objects, and methods in Java. It explains how to create and manipulate objects, the importance of access modifiers and data hiding, and includes examples of writing classes and methods. Additionally, it covers basic Java syntax, data types, arithmetic operations, and the scope of variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views47 pages

Lecture 2

The document provides an overview of Object-Oriented Programming concepts, focusing on classes, objects, and methods in Java. It explains how to create and manipulate objects, the importance of access modifiers and data hiding, and includes examples of writing classes and methods. Additionally, it covers basic Java syntax, data types, arithmetic operations, and the scope of variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Faculty of Information Technology

Fall 2020/21

Object-Oriented Programming
CS-201, CS201

Lec. (2)
Objects and Classes
– A class is code that describes a particular type of object. It specifies the
data that an object can hold (the object's fields), and the actions that an
object can perform (the object's methods).

– You can think of a class as a code "blueprint" that can be used to create
a particular type of object.
Objects and Classes
• When a program is running, it can use the class to create, in
memory, as many objects of a specific type as needed.

• Each object that is created from a class is called an instance of


the class.
Objects and Classes
This expression creates a
Example: Scanner object in memory.

Scanner keyboard = new Scanner(System.in);

The object's memory address


is assigned to the keyboard
variable.

keyboard Scanner
variable object
Writing a Class, Step by Step
• A Room object will have the following fields:
Room

length
width
height
setLength()
setWidth()
setHeight()
getLength()
getWidth()
getHeight()
getArea()
Writing the Code
public class Room Room
{
length
private double length; width
height
private double width; setLength()
} setWidth()
setHeight()
getLength()
getWidth()
getHeight()
getArea()
Access Modifiers
• An access modifier is a Java keyword that indicates how a field or method can
be accessed.
• public
– When the public access modifier is applied to a class member, the member can be
accessed by code inside the class or outside.
• private
– When the private access modifier is applied to a class member, the member cannot be
accessed by code outside the class. The member can be accessed only by methods that
are members of the same class.

Data Hiding
Data Hiding
• An object hides its internal, private fields from code that is outside the class
that the object is an instance of.
• Only the class's methods may directly access and change the object’s internal
data.
• Code outside the class must use the class's public methods to operate on an
object's private fields.
• Data hiding is important because classes are typically used as components in
large software systems, involving a team of programmers.
• Data hiding helps enforce the integrity of an object's internal data.
Return Room
Type
Access Method - width : double
Name - length : double
specifier
- height : double
+ setWidth(w : double) : void
+ setLength(len : double): void
+ getWidth() : double
public void setLength(double len) + getLength() : double
+ getArea() : double

Parameter variable declaration


public class Room
{
private double length;
private double width;
public void setLength(double len)
{
length = len;
}

}
Creating a Room object
Room r = new Room ();

The r Room object


variable holds length: 0.0
the address of address
the Room width: 0.0
object. Height: 0.0
Calling the setLength Method

r.setLength(10.0);
The r A Room object
variable holds width:
the address of address
the Room 0.0
object.

This is the state of the r object after


the setLength method executes.

6-32
Writing the getLength Method
public class Room
{
private double length;
private double width;
public void setLength(double len)
{
length = len;
}
public double getLength()
{
return length;
}
}

6-33
public class Room
{
private double width;
private double length;

public void setWidth(double w)


{ width = w;
}
public void setLength(double len)
{ length = len;
}
public double getWidth()
{ return width;
}
public double getLength()
{ return length;
}
public double getArea()
{ return length * width;
}
}
Instance Fields and Methods
• Fields and methods that are declared as previously shown are called
instance fields and instance methods.
• Objects created from a class each have their own copy of instance
fields.
• Instance methods are methods that are not declared with a special
keyword, static.
Instance Fields and Methods

• Instance fields and instance methods require an object to be


created in order to be used.
• For example, every room can have different dimensions.

Room kitchen = new Room();


Room bedroom = new Room();
Room Lounge = new Room();
States of Three Different Room Objects

The kitchen variable


length: 4.0
holds the address of a address
Room Object.
width: 5.0
length: 5.0
The bedroom variable Height 4.0
holds the address of a address width: 6.0
Room Object.
Height 4.0
The longue
variable holds the length: 30.0
address
address of a Room
Object. width: 20.0

Height 10.0
Accessors and Mutators
public class Rectangle
{
private double width;
private double length;

public void setWidth(double w)


{ width = w; Setter , Mutator
}
public void setLength(double len)
{ length = len;
}
public double getWidth()
{ return width;
}
public double getLength() Getter, Accessor
{ return length;
}
public double getArea()
{ return length * width;
}
}
Objects and Classes
This expression creates a
Example: Scanner object in memory.

Scanner Input= new Scanner(System.in);

The object's memory address


is assigned to the Input
variable.

Input Scanner
variable object
Uninitialized Local Reference Variables
• Reference variables can be declared without being initialized.
Room r1;
• This statement does not create a Room object, so it is an uninitialized local
reference variable.
• A local reference variable must reference an object before it can be used, otherwise a
compiler error will occur.
r1 = new Room();

Box Rectangle
variable object
More Examples
Your First Java Program
Processing a Java Program
Create/Modify Source Code

Source code (developed by the programmer)


Saved on the disk
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Source Code
}
}

Compile Source Code


Byte code (generated by the compiler for JVM i.e., javac Welcome.java
to read and interpret, not for you to understand)

Method Welcome() If compilation errors
0 aload_0 stored on the disk

Bytecode
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
Run Byteode
i.e., java Welcome

Result

If runtime errors or incorrect result


Programming Errors
• Syntax Errors
– Detected by the compiler

• Runtime Errors
– Causes the program to abort

• Logic Errors
– Produces incorrect result
Comments

• We can put comment on our programs using


• // to comment a single line
// this progrm is written by Khaled

• /*
Mulitple Lines
• */ to comment multiple lines

/* This program is written by Khaled On Thursday 8/11/2020


*/
Interacting With User: Displaying Messages on Screen
• In Java, we use System.out.print ( ) Or System.out.println () To be Display text on The screen
Interacting With User: Displaying Messages on Screen

• He said that “Iam From Egypt”


– System.out.print(“ He Said That \“Iam From Egypt \” “)
- -
import java.util.Scanner;

import java.util.Scanner;
public class Addition {
public static void main (String[] args)
{
//II create a Scanner to obtain i nput from the command window
Scanner input = new Scanner (System.in);
System.out.print ("Enter first integer:");
int numberl = input.nextInt();
System.out.print("Enter second integer: ");
int number2 = input.nextInt();
int sum = numberl + number2;
System.out.printf("Sum= is %d%n", sum);
}
}
Java Data Types
char Character or small 1byte signed: -128 to 127
integer. unsigned: 0 to 255
int Integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295

short int (short) Short Integer. 2bytes signed: -32768 to 32767


unsigned: 0 to 65535
long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295

bool Boolean value. It can 1byte true or false


take one of two values:
true or false.
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision 8bytes +/- 1.7e +/- 308 (~15 digits)
floating point number.
long double Long double precision 8bytes +/- 1.7e +/- 308 (~15 digits)
floating point number.
Interacting With User: Accept Input From User
• A variable is a location in the computer’s memory where a value can be stored for use by a program.
• All variables must be declared with a name and a data type before they can be used in a program.
• Declaration : DataType Identifier
Example 1
• Write a program to find the Area of a rectangle

The area of the Rectangle are given by the following formula:

Area = Rect Length * Rect Width.

Input :
Rectangle Length , Rectangle Width.

Processing :
Area = Rect Length * Rect Width.

Output :
Print Out The area.
Working With Variable
5
Int length ; Length
Int width; 10
Int area; Width

50
Scanner input = new Scanner(System.in); area

Length = input.nextInt();

Width = input.nextInt();

Area = Length * width ;


Example 2
• Write a program to find the perimeter and area of a square

The perimeter and area of the square are given by the following formulas:
perimeter = Side Length * 4
area = Side Length * Side Length
Input:
Square Side Length
Processing:
perimeter = Side Length * 4
area = Side Length * Side Length
Output:
Print Out The Perimeter and Area.
Arithmetic Operations

Name Meaning Example Result


+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

34
Precedence of arithmetic operations

For example, 2 + 3 * 5 and (2 + 3) * 5

both have different meanings


Precedence of arithmetic operations
Example:
36
Precedence of arithmetic operations

• )4 + 3( * 2 + 1 = ?

– Evaluated as ))3+4( *2 ( +1 and the result is 15


• 4%9+2*5=?

– Evaluated as )4 %9 ( + )2*5(and the result is 11


• )4 – 7 ( % 2 * 5 = ?

– Evaluated as )4 –7 ( % )2 *5 (and the result is 1


Data Type of an Arithmetic Expression
• Data type of an expression depends on the type of its operands
– Data type conversion is done by the compiler

• If operators are *, /, +, or – , then the type of the result will be:


– integer, if all operands are integer.
» Int A , B;
» A+ B  Integer.
– float, If at least one operand is float and there is no double
» Int A ; Float B;
» A + B  Float.
– double, if at least one operand is double
• Int A ; Float B; Double C;
» A + B + C  double.
Increment and Decrement Operators

• Increment operator: increment variable by 1


– Pre-increment: ++variable
– Post-increment: variable++

• Decrement operator: decrement variable by 1


– Pre-decrement: --variable
– Post-decrement: variable --

• Examples :
++K , K++  k= K+1
--K , K--  K= K-1
Increment and Decrement Operators
• If the value produced by ++ or – – is not used in an expression, it does not matter whether it is a
pre or a post increment (or decrement).

• When ++ (or – –) is used before the variable name, the computer first increments (or decrements)
the value of the variable and then uses its new value to evaluate the expression.

• When ++ (or – –) is used after the variable name, the computer uses the current value of the
variable to evaluate the expression, and then it increments (or decrements) the value of the
variable.

• There is a difference between the following

x = 5;
Print(++x);
x = 5;
Print (x++);
special assignment statements

• Java has special assignment statements called compound assignments

+= , -= , *= , /= , %=
• Example:
X +=5 ; means x = x + 5;
x *=10; means x = x * 10;
x /=5; means x = x / 5;
For Example : write a program that ask the user to Enter 3 integer numbers and print out their sum
and Average.

int main ()
{
int n1 , n2 , n3 ;
System.out.println("Please Enter 3 integer numbers “ );
n1= input.nextInt();
n2= input.nextInt();
n3= input.nextInt();
System.out.println(" The sum of the 3 number is “ || sum (n1, n2,n3) );
System.out.println(" The average of the 3 number is " || average (n1, n2,n3) );
}
Public static int sum (int num1 , int num2, int num3)
{
return num1+num2+num3;
}

Public static double average (int num1, int num2, int num3 )
{
return sum (num1 , num2 , num3)/3 ;
}
Scope of a variable
scope is the context within a program in which a variable is valid and can be used.

– Local variable: declared within a function (or block)


– can be accessible only within the function or from declaration to the end of the block.
– Within nested blocks if no variable with same name exists.

int sum (int x , int y ) int main ( )


{ {
int result ; {
Int x ;

result = x + y;
return result; }
} } 128
Scope of a variable
Global variable: declared outside of every function definition.
– Can be accessed from any function that has no local variables with the same name. In case the function
has a local variable with the same name as the global variable ,
static Int z ;
int main ( )
{
{

}
}
int sum (int x , int y )
{

}
Scope of a variable
Static int x = 100 ;
int main ( )
{
int x= 10;

{
int z , x ;
z=100;
y=100;
x= 250;
System.out.println(" inner block " << x ;
}
}
 Method Overloading:
Defining several methods within a class with the same name. As long as every Method has a
different signature
 Method Signature:
The signature of a method consists of the following:
 Method name
 Formal parameter list

Note that the method type is not part of its signature.

 Examples:
 public int Sum(int x, int y)
 public int Sum(int x, int y , int z)
 public double Sum(double x, double y, double z)
 public int Sum(int x, double y)
 public int Sum(double y, int x) 133
 The following methods are incorrectly overloaded; the compiler generates an error:

 Example (1): The following methods are incorrectly overloaded because they have the same
method name and same formal parameter lists:

 public void methodABC (int x, double y)


 public int methodABC (int x, double y)

 Example (2): Changing the names of the formal parameters, does not allow overloading of the
previous counter-example:

 public void methodABC (int x, double y)


 public int methodABC (int num1, double num2)
 Counter-example (3): Adding the modifier static does not allow
overloading of the previous example:
 public static void methodABC (int x, double y)
 public int methodABC (int num1, double num2)

Note that the method type and modifiers are not part of the overloading rules

You might also like