SlideShare a Scribd company logo
Methods
int month;
int year
class Month
Defining Classes
• A class contains data declarations (static and
instance variables) and method declarations
(behaviors)
Data declarations
Method declarations
Methods
• A program that provides some functionality can be long
and contains many statements
• A method groups a sequence of statements and should
provide a well-defined, easy-to-understand functionality
– a method takes input, performs actions, and produces output
• In Java, each method is defined within specific class
Method Declaration: Header
• A method declaration begins with a method
header
method
name
return
type
parameter list
The parameter list specifies the type
and name of each parameter
The name of a parameter in the method
declaration is called a formal argument
class MyClass
{
static int min ( int num1, int num2 )
…
properties
Method Declaration: Body
The header is followed by the method body:
static int min(int num1, int num2)
{
int minValue = num1 < num2 ? num1 : num2;
return minValue;
}
class MyClass
{
…
…
}
6
The return Statement
• The return type of a method indicates the
type of value that the method sends back
to the calling location
– A method that does not return a value has a
void return type
• The return statement specifies the value
that will be returned
– Its expression must conform to the return type
Calling a Method
• Each time a method is called, the values of
the actual arguments in the invocation are
assigned to the formal arguments
static int min (int num1, int num2)
{
int minValue = (num1 < num2 ? num1 : num2);
return minValue;
}
int num = min (2, 3);
Method Control Flow
• A method can call another method, who
can call another method, …
min(num1, num2, num3) println()
…println(…)
min(1, 2, 3);
main
9
Method Overloading
• A class may define multiple methods with the same
name---this is called method overloading
– usually perform the same task on different data types
• Example: The PrintStream class defines multiple println
methods, i.e., println is overloaded:
println (String s)
println (int i)
println (double d)
…
• The following lines use the System.out.print method for
different data types:
System.out.println ("The total is:");
double total = 0;
System.out.println (total);
10
Method Overloading: Signature
• The compiler must be able to determine which
version of the method is being invoked
• This is by analyzing the parameters, which form
the signature of a method
– the signature includes the type and order of the
parameters
• if multiple methods match a method call, the compiler picks
the best match
• if none matches exactly but some implicit conversion can be
done to match a method, then the method is invoke with
implicit conversion.
– the return type of the method is not part of the
signature
Method Overloading
double tryMe (int x)
{
return x + .375;
}
Version 1
double tryMe (int x, double y)
{
return x * y;
}
Version 2
result = tryMe (25, 4.32)
Invocation
More Examples
double tryMe ( int x )
{
return x + 5;
}
double tryMe ( double x )
{
return x * .375;
}
double tryMe (double x, int y)
{
return x + y;
}
tryMe( 1 );
tryMe( 1.0 );
tryMe( 1.0, 2);
tryMe( 1, 2);
tryMe( 1.0, 2.0);
Which tryMe will be called?
Variable Scoping
Variables
• At a given point, the variables that a
statement can access are determined by the
scoping rule
– the scope of a variable is the section of a program
in which the variable can be accessed (also called
visible or in scope)
• There are two types of scopes in Java
– class scope
• a variable defined in a class but not in any method
– block scope
• a variable defined in a block {} of a method; it is also
called a local variable
Java Scoping Rule
• A variable with a class scope
– class/static variable: a variable defined in class scope and has the
static property
• it is associated with the class
• and thus can be accessed (in scope) in all methods in the class
– instance variable: a variable defined in class scope but not static
• it is associated with an instance of an object of the class,
• and thus can be accessed (in scope) only in instance methods, i.e., those
non-static methods
• A variable with a block scope
– can be accessed in the enclosing block; also called local variable
– a local variable can shadow a variable in a class scope with the same
name
• Do not confuse scope with duration
– a variable may exist but is not accessible in a method,
• e.g., method A calls method B, then the variables declared in method A exist
but are not accessible in B.
Scoping Rules (cont.):
Variables in a method
• There are can be three types of variables
accessible in a method :
– class and instance variables
• static and instance variables of the class
– local variables
• those declared in the method
– formal arguments
Example1:
public class Box
{
private int length, width;
…
public int widen (int extra_width)
{
private int temp1;
size += extra_width;
…
}
public int lenghten (int extra_lenth)
{
private int temp2;
size += extra_length;
…
}
…
}
• instance variables
• formal arguments
• local variables
Scope of Variables
• Instance variables
are accessible in all
methods of the
class
• formal arguments
are valid within their
methods
• Local variables are
valid from the point
of declaration to the
end of the enclosing
block
public class Box
{
private int length, width;
…
public int widen (int extra_width)
{
private int temp1;
size += extra_width;
…
}
public int lenghten (int extra_lenth)
{
private int temp2;
size += extra_length;
…
}
…
}
public class Test
{
final static int NO_OF_TRIES = 3;
static int i = 100;
public static int square ( int x )
{
// NO_OF_TRIES, x, i in scope
int mySquare = x * x;
// NO_OF_TRIES, x, i, mySquare in scope
return mySquare;
}
public static int askForAPositiveNumber ( int x )
{
// NO_OF_TRIES, x, i in scope
for ( int i = 0; i < NO_OF_TRIES; i++ )
{ // NO_OF_TRIES, x, i in scope; local i shadows class i
System.out.print(“Input: “);
Scanner scan = new Scanner( System.in );
String str = scan.nextLine();
int temp = Integer.parseInt( str );
// NO_OF_TRIES, x, i, scan, str, temp in scope
if (temp > 0) return temp;
}
// NO_OF_TRIES, x, i in scope
return 0;
} // askForPositiveNumber
public static void main( String[] args )
{…}
Two Types of
Parameter Passing
• If a modification of the formal argument
has no effect on the actual argument,
– it is call by value
• If a modification of the formal argument
can change the value of the actual
argument,
– it is call by reference
Call-By-Value and
Call-By-Reference in Java
• Depend on the type of the formal argument
• If a formal argument is a primitive data type, a
modification on the formal argument has no effect on
the actual argument
– this is call by value, e.g. num1 = min(2, 3);
num2 = min(x, y);
• This is because primitive data types variables contain
their values, and procedure call trigger an assignment:
<formal argument> = <actual argument>
int x = 2; int y = 3;
int num = min (x, y);
…
static int num( int num1, int num2)
{ … }
int x = 2;
int y = 3;
int num1 = x;
int num2 = y;
{ … }
Call-By-Value and
Call-By-Reference in Java
• If a formal argument is not a primitive data type, an
operation on the formal argument can change the
actual argument
– this is call by reference
• This is because variables of object type contain
pointers to the data that represents the object
• Since procedure call triggers an assignment
<formal argument> = <actual argument>
it is the pointer that is copied, not the object itself!
MyClass x = new MyClass();
MyClass y = new MyClass();
MyClass.swap( x, y);
…
static void swap( MyClass x1, MyClass x2)
{ … }
x = new MC();
y = new MC();
x1 = x;
x2 = y;
{ … }
Class design
24
Classes define Objects
• In object-oriented design, we group methods together
according to objects on which they operate
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or be done to it), may depend on
the state, and can change the state
• For example, a calendar program needs Month objects:
– the state of a Month object is a (month,year) pair of numbers
– these are stored as instance variables of the Month class
– the Month class can also have class variables, e.g. the day of
the week that Jan 1, 2000 falls on…
– some behaviors of a month object are:
• get name, get first weekday, get number of days,
• print
• set month index, set year
int month;
int year
class Month
Defining Classes
• A class contains data declarations (state)
and method declarations (behaviors)
Data declarations
Method declarations
Method Types
• There can be various types of methods (behavior
declarations)
– access methods : read or display states (or those that can be
derived)
– predicate methods : test the truth of some conditions
– action methods, e.g., print
– constructors: a special type of methods
• they have the same name as the class
– there may be more then one constructor per class
(overloaded constructors)
• they do not return any value
– it has no return type, not even void
• they initialize objects of the class, using the new construct:
– e.g. m1 = new Month();
• you do not have to define a constructor
– the value of the state variables have default value
Example: Month class
• We define a Month class to model a month in the
calendar program
• In our Month class we could define the following data:
– month, an integer that represents the index of month
– year, an integer that represents the year the month is in
• We might also define the following methods:
– a Month constructor, to set up the month
– a getName method, to ask for the string name of a month obj.
– a getNumberOfDays method, to ask for the no. of days of a
month object
– a getFirstWeekday method, to ask for the weekday of the
first day of a month object
– a print method, to print the month calendar
– a setMonth method, to ask a month object to change its month
– a setYear object, to ask a month object to change its year

More Related Content

What's hot

Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
kjkleindorfer
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
Ferdin Joe John Joseph PhD
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
Tareq Hasan
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
M Vishnuvardhan Reddy
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
Fajar Baskoro
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
maznabili
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
Atul Sehdev
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
Dennis Chang
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
Hoang Nguyen
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
UniSoftCorner Pvt Ltd India.
 
Method of java
Method of javaMethod of java
Method of java
Niloy Biswas
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 

What's hot (20)

Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Method of java
Method of javaMethod of java
Method of java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 

Similar to Lec4

Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
Explain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptExplain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
AshokKumar587867
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 

Similar to Lec4 (20)

Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Explain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptExplain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).ppt
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Chap08
Chap08Chap08
Chap08
 
Hemajava
HemajavaHemajava
Hemajava
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Delegate
DelegateDelegate
Delegate
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Core java oop
Core java oopCore java oop
Core java oop
 

Recently uploaded

Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 

Lec4

  • 2. int month; int year class Month Defining Classes • A class contains data declarations (static and instance variables) and method declarations (behaviors) Data declarations Method declarations
  • 3. Methods • A program that provides some functionality can be long and contains many statements • A method groups a sequence of statements and should provide a well-defined, easy-to-understand functionality – a method takes input, performs actions, and produces output • In Java, each method is defined within specific class
  • 4. Method Declaration: Header • A method declaration begins with a method header method name return type parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument class MyClass { static int min ( int num1, int num2 ) … properties
  • 5. Method Declaration: Body The header is followed by the method body: static int min(int num1, int num2) { int minValue = num1 < num2 ? num1 : num2; return minValue; } class MyClass { … … }
  • 6. 6 The return Statement • The return type of a method indicates the type of value that the method sends back to the calling location – A method that does not return a value has a void return type • The return statement specifies the value that will be returned – Its expression must conform to the return type
  • 7. Calling a Method • Each time a method is called, the values of the actual arguments in the invocation are assigned to the formal arguments static int min (int num1, int num2) { int minValue = (num1 < num2 ? num1 : num2); return minValue; } int num = min (2, 3);
  • 8. Method Control Flow • A method can call another method, who can call another method, … min(num1, num2, num3) println() …println(…) min(1, 2, 3); main
  • 9. 9 Method Overloading • A class may define multiple methods with the same name---this is called method overloading – usually perform the same task on different data types • Example: The PrintStream class defines multiple println methods, i.e., println is overloaded: println (String s) println (int i) println (double d) … • The following lines use the System.out.print method for different data types: System.out.println ("The total is:"); double total = 0; System.out.println (total);
  • 10. 10 Method Overloading: Signature • The compiler must be able to determine which version of the method is being invoked • This is by analyzing the parameters, which form the signature of a method – the signature includes the type and order of the parameters • if multiple methods match a method call, the compiler picks the best match • if none matches exactly but some implicit conversion can be done to match a method, then the method is invoke with implicit conversion. – the return type of the method is not part of the signature
  • 11. Method Overloading double tryMe (int x) { return x + .375; } Version 1 double tryMe (int x, double y) { return x * y; } Version 2 result = tryMe (25, 4.32) Invocation
  • 12. More Examples double tryMe ( int x ) { return x + 5; } double tryMe ( double x ) { return x * .375; } double tryMe (double x, int y) { return x + y; } tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); Which tryMe will be called?
  • 14. Variables • At a given point, the variables that a statement can access are determined by the scoping rule – the scope of a variable is the section of a program in which the variable can be accessed (also called visible or in scope) • There are two types of scopes in Java – class scope • a variable defined in a class but not in any method – block scope • a variable defined in a block {} of a method; it is also called a local variable
  • 15. Java Scoping Rule • A variable with a class scope – class/static variable: a variable defined in class scope and has the static property • it is associated with the class • and thus can be accessed (in scope) in all methods in the class – instance variable: a variable defined in class scope but not static • it is associated with an instance of an object of the class, • and thus can be accessed (in scope) only in instance methods, i.e., those non-static methods • A variable with a block scope – can be accessed in the enclosing block; also called local variable – a local variable can shadow a variable in a class scope with the same name • Do not confuse scope with duration – a variable may exist but is not accessible in a method, • e.g., method A calls method B, then the variables declared in method A exist but are not accessible in B.
  • 16. Scoping Rules (cont.): Variables in a method • There are can be three types of variables accessible in a method : – class and instance variables • static and instance variables of the class – local variables • those declared in the method – formal arguments
  • 17. Example1: public class Box { private int length, width; … public int widen (int extra_width) { private int temp1; size += extra_width; … } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; … } … } • instance variables • formal arguments • local variables
  • 18. Scope of Variables • Instance variables are accessible in all methods of the class • formal arguments are valid within their methods • Local variables are valid from the point of declaration to the end of the enclosing block public class Box { private int length, width; … public int widen (int extra_width) { private int temp1; size += extra_width; … } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; … } … }
  • 19. public class Test { final static int NO_OF_TRIES = 3; static int i = 100; public static int square ( int x ) { // NO_OF_TRIES, x, i in scope int mySquare = x * x; // NO_OF_TRIES, x, i, mySquare in scope return mySquare; } public static int askForAPositiveNumber ( int x ) { // NO_OF_TRIES, x, i in scope for ( int i = 0; i < NO_OF_TRIES; i++ ) { // NO_OF_TRIES, x, i in scope; local i shadows class i System.out.print(“Input: “); Scanner scan = new Scanner( System.in ); String str = scan.nextLine(); int temp = Integer.parseInt( str ); // NO_OF_TRIES, x, i, scan, str, temp in scope if (temp > 0) return temp; } // NO_OF_TRIES, x, i in scope return 0; } // askForPositiveNumber public static void main( String[] args ) {…}
  • 20. Two Types of Parameter Passing • If a modification of the formal argument has no effect on the actual argument, – it is call by value • If a modification of the formal argument can change the value of the actual argument, – it is call by reference
  • 21. Call-By-Value and Call-By-Reference in Java • Depend on the type of the formal argument • If a formal argument is a primitive data type, a modification on the formal argument has no effect on the actual argument – this is call by value, e.g. num1 = min(2, 3); num2 = min(x, y); • This is because primitive data types variables contain their values, and procedure call trigger an assignment: <formal argument> = <actual argument> int x = 2; int y = 3; int num = min (x, y); … static int num( int num1, int num2) { … } int x = 2; int y = 3; int num1 = x; int num2 = y; { … }
  • 22. Call-By-Value and Call-By-Reference in Java • If a formal argument is not a primitive data type, an operation on the formal argument can change the actual argument – this is call by reference • This is because variables of object type contain pointers to the data that represents the object • Since procedure call triggers an assignment <formal argument> = <actual argument> it is the pointer that is copied, not the object itself! MyClass x = new MyClass(); MyClass y = new MyClass(); MyClass.swap( x, y); … static void swap( MyClass x1, MyClass x2) { … } x = new MC(); y = new MC(); x1 = x; x2 = y; { … }
  • 24. 24 Classes define Objects • In object-oriented design, we group methods together according to objects on which they operate • An object has: – state - descriptive characteristics – behaviors - what it can do (or be done to it), may depend on the state, and can change the state • For example, a calendar program needs Month objects: – the state of a Month object is a (month,year) pair of numbers – these are stored as instance variables of the Month class – the Month class can also have class variables, e.g. the day of the week that Jan 1, 2000 falls on… – some behaviors of a month object are: • get name, get first weekday, get number of days, • print • set month index, set year
  • 25. int month; int year class Month Defining Classes • A class contains data declarations (state) and method declarations (behaviors) Data declarations Method declarations
  • 26. Method Types • There can be various types of methods (behavior declarations) – access methods : read or display states (or those that can be derived) – predicate methods : test the truth of some conditions – action methods, e.g., print – constructors: a special type of methods • they have the same name as the class – there may be more then one constructor per class (overloaded constructors) • they do not return any value – it has no return type, not even void • they initialize objects of the class, using the new construct: – e.g. m1 = new Month(); • you do not have to define a constructor – the value of the state variables have default value
  • 27. Example: Month class • We define a Month class to model a month in the calendar program • In our Month class we could define the following data: – month, an integer that represents the index of month – year, an integer that represents the year the month is in • We might also define the following methods: – a Month constructor, to set up the month – a getName method, to ask for the string name of a month obj. – a getNumberOfDays method, to ask for the no. of days of a month object – a getFirstWeekday method, to ask for the weekday of the first day of a month object – a print method, to print the month calendar – a setMonth method, to ask a month object to change its month – a setYear object, to ask a month object to change its year