SlideShare una empresa de Scribd logo
1 de 17
Returning values from methods 
A method which has a non-void return type MUST return a 
value 
The return value's type must match the type defined in the method's 
signature. 
A void method can use a return statement (with no return value) to exit 
the method. 
The return value can be used the same as any other expression. 
public class Car 
{ 
private int currentGear; 
private int currentRpms; 
public int calculateSpeed() 
{ 
return currentRpms * currentGear; 
} 
}
Classes as types 
When a class is defined, the compiler regards the class as a 
new type. 
When a variable is declared, its type can be a primitive type or 
"Class" type. 
Any variable whose type is a class is an object reference. 
The variable is a reference to an instance of the specified class. 
The variables holds the address (in memory) of the object. 
int x; 
0 
Employee anEmployee; 
null 
Note: null means 
“refers to no 
object”
null References 
null means “refers to no object" 
Object references can be compared to null to see if an object 
is present or not. 
null is the default value of an object reference before it is 
initialized 
Employee anEmployee; 
[...] 
if (anEmployee == null) 
{ 
}
Initializing Object References - new 
To initialize an object reference, you must assign it the 
address of an object 
The new operator creates a new instance and returns the 
address of the newly created object 
new allocates memory for the object 
new also invokes a method on the object called a constructor 
new returns the address of the memory allocated for the object. 
Employee anEmployee; 
[...] 
anEmployee = new Employee();
Assigning Object References 
Assigning one reference to another results in two references 
to the same object 
If two references contain the same memory address, they are referring 
to the same object. 
Remember testing for equality of Strings using == 
Each object has a reference count 
When an object's reference count becomes zero, it will be collected by 
the garbage collector 
Employee anEmployee = new Employee(); 
Employee anotherEmployee = anEmployee; 
Employee 
anEmployee 
anotherEmployee
Invoking Instance Methods 
To invoke a method on an object, use the . (dot) operator 
objectReference.methodName(parameters); 
• If there is a return value, it can be used as an expression 
Car aCar = new Car(); 
[...] 
if (aCar.calculateSpeed()>110) 
{ 
System.out.println("You're Speeding!"); 
} 
[...]
Passing Parameters to Methods 
Method parameters are declared in the method's signature. 
When a method invocation is made, any parameters included 
in the invocation are passed to the method 
All parameters are passed by value. Ie, a copy is made 
The value of fundamental data types are copied 
The value of object references (ie memory addresses) are copied 
• Parameters become variables within the method. They are 
not known outside the method. 
public float calculateInterestForMonth(float rate) 
{ 
return lowBalanceForMonth * (rate/12.0); 
}
Overloading Methods 
Java allows for method overloading. 
A Method is overloaded when the class provides several 
implementations of the same method, but with different 
parameters 
The methods have the same name 
The methods have differing numbers of parameters or different types of 
parameters 
The return type MUST be the same 
public float calculateInterestForMonth() 
{ 
return lowBalanceForMonth * (defaultRate/12.0); 
} 
public float calculateInterestForMonth(float rate) 
{ 
return lowBalanceForMonth * (rate/12.0); 
}
Accessor Methods - gets 
Objects have variables. 
Because of encapsulation, those variables are generally private 
However, the outside world may need to use those variables 
The class implementor may choose to add a "get" method to return the 
value 
The usual name of the get method is the name of the variable 
prefixed with the word "get" 
getName(), getAddress(), getPhone(), getBalance() 
public class BankAccount 
{ 
private float balance; 
public float getBalance() 
{ 
return balance; 
}
Accessor Methods - sets 
Similarly, the outside world may need to set the value of an 
instance variable 
The class implementor may choose to implement a set method. 
The responsibility of the set method is to set the appropriate variable 
WHILST MAINTAINING data integrity of the object. 
The usual name of the set method is the name of the variable 
prefixed with the word "set" 
setName(), setAddress(), setPhone(), setBalance() 
public class BankAccount 
{ 
private String ownerName; 
public void setOwnerName(String aName) 
{ 
ownerName = aName; 
}
Design Issues - When to provide gets and sets 
Get and set often provide confusion for novice programmers 
Do all instance variables have them? 
If so, why don't we make the instance variables public and access them 
directly? 
Don't gets and sets violate encapsulation? 
Whether a variable has an associated get and set method is a 
design issue; it is not a coding issue. 
Imagine a BankAccount Class 
All Bank Accounts have Account Numbers 
Once an Account's Account Number has been set, should it 
be changeable? 
• If we don't provide a set method, how do we initialize the 
variable in the first place?
Initializing Objects - Constructors 
When an object is created, all instance variables are initialized 
to the default value for their type 
Fundamentals are 0, 0.0, '000' or false 
Object references are null 
In order to put the object into a usable state, its instance 
variables should be initialized to usable values 
This could be accomplished by calling the various set methods 
This is not always possible because it is not required that all instance 
variables have set methods. 
Java provides for another method of initializing objects 
When an object is created, a constructor is invoked. The 
responsibility of the constructor method is to initialize the 
object into a usable state.
Constructors 
Constructors have the following characteristics 
There is NO return type. NOT even void 
The method name is the same name as the class 
Constructors can be overloaded 
In order to put the object into a usable state, its instance 
variables should be initialized to usable values 
This could be accomplished by calling the various set methods 
This is not always possible because it is not required that all instance 
variables have set methods. 
Java provides for another method of initializing objects 
When an object is created (using new), a constructor is 
invoked. The responsibility of the constructor method is to 
initialize the object into a usable state.
Constructors - Example 
public class BankAccount 
{ 
String ownersName; 
int accountNumber; 
float balance; 
public BankAccount() 
{ 
} 
public BankAccount(int anAccountNumber) 
{ 
accountNumber = anAccountNumber; 
} 
public BankAccount(int anAccountNumber, String aName) 
{ 
accountNumber = anAccountNumber; 
ownersName = aName; 
} 
[...] 
}
Constructors - Example 
When an object is created (using new) the compiler 
determines which constructor is to be invoked by the 
parameters passed 
Multiple constructors allows the class programmer to define many 
different ways of creating an object. 
public static void main(String[] args) 
{ 
BankAccount anAccount = new BankAccount(); 
BankAccount anotherAccount = new BankAccount(12345); 
BankAccount myAccount = new BankAccount(33423, "Craig"); 
}
Constructors 
If no constructors are defined for a class, the compiler 
automatically generates a default, no argument constructor 
All instance variables are initialized to default values. 
However, if any constructor is defined which takes 
parameters, the compiler will NOT generate the default, no 
argument constructor 
If you still need one, you have to explicitly define one.
Review 
What is the difference between classes and objects? 
What are the modifiers for classes, instance variables and 
methods? What do they mean? 
What is encapsulation? Why is it important? 
How are method parameters defined? 
How are method parameters passed? 
How do accessor methods support encapsulation? 
What are constructors?

Más contenido relacionado

La actualidad más candente

Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1
tam53pm1
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotations
Krazy Koder
 
Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
vikram singh
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 

La actualidad más candente (20)

Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
C# Generics
C# GenericsC# Generics
C# Generics
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and events
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1
 
Java operators
Java operatorsJava operators
Java operators
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotations
 
Module 15 attributes
Module 15 attributesModule 15 attributes
Module 15 attributes
 
Java Script Language Tutorial
Java Script Language TutorialJava Script Language Tutorial
Java Script Language Tutorial
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 

Destacado (9)

Building A Financial Foundation
Building A Financial FoundationBuilding A Financial Foundation
Building A Financial Foundation
 
Chapter 3 building foundation
Chapter 3 building foundationChapter 3 building foundation
Chapter 3 building foundation
 
Making ourselves redundant: Delivering impact by building design capabilities...
Making ourselves redundant: Delivering impact by building design capabilities...Making ourselves redundant: Delivering impact by building design capabilities...
Making ourselves redundant: Delivering impact by building design capabilities...
 
Foundation and its types
Foundation and its typesFoundation and its types
Foundation and its types
 
Machine Foundation Design
Machine Foundation Design Machine Foundation Design
Machine Foundation Design
 
Multi storey building design of 7 storey commercial building
Multi storey building design of 7 storey commercial buildingMulti storey building design of 7 storey commercial building
Multi storey building design of 7 storey commercial building
 
Types Of Foundation
Types Of FoundationTypes Of Foundation
Types Of Foundation
 
Architectural Professional Practice - Design
Architectural Professional Practice - DesignArchitectural Professional Practice - Design
Architectural Professional Practice - Design
 
types of bridges
types of bridgestypes of bridges
types of bridges
 

Similar a Synapseindia strcture of dotnet development part 2

Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 

Similar a Synapseindia strcture of dotnet development part 2 (20)

Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
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...
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
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
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
 
Classes2
Classes2Classes2
Classes2
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Oop
OopOop
Oop
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Constructors
ConstructorsConstructors
Constructors
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 

Más de Synapseindiappsdevelopment

Más de Synapseindiappsdevelopment (20)

Synapse india elance top in demand in it skills
Synapse india elance top in demand in it skillsSynapse india elance top in demand in it skills
Synapse india elance top in demand in it skills
 
SynapseIndia dotnet web development architecture module
SynapseIndia dotnet web development architecture moduleSynapseIndia dotnet web development architecture module
SynapseIndia dotnet web development architecture module
 
SynapseIndia dotnet module development part 1
SynapseIndia  dotnet module development part 1SynapseIndia  dotnet module development part 1
SynapseIndia dotnet module development part 1
 
SynapseIndia dotnet framework library
SynapseIndia  dotnet framework librarySynapseIndia  dotnet framework library
SynapseIndia dotnet framework library
 
SynapseIndia dotnet development platform overview
SynapseIndia  dotnet development platform overviewSynapseIndia  dotnet development platform overview
SynapseIndia dotnet development platform overview
 
SynapseIndia dotnet development framework
SynapseIndia  dotnet development frameworkSynapseIndia  dotnet development framework
SynapseIndia dotnet development framework
 
SynapseIndia dotnet web applications development
SynapseIndia  dotnet web applications developmentSynapseIndia  dotnet web applications development
SynapseIndia dotnet web applications development
 
SynapseIndia dotnet website security development
SynapseIndia  dotnet website security developmentSynapseIndia  dotnet website security development
SynapseIndia dotnet website security development
 
SynapseIndia mobile build apps management
SynapseIndia mobile build apps managementSynapseIndia mobile build apps management
SynapseIndia mobile build apps management
 
SynapseIndia mobile apps deployment framework internal architecture
SynapseIndia mobile apps deployment framework internal architectureSynapseIndia mobile apps deployment framework internal architecture
SynapseIndia mobile apps deployment framework internal architecture
 
SynapseIndia java and .net development
SynapseIndia java and .net developmentSynapseIndia java and .net development
SynapseIndia java and .net development
 
SynapseIndia dotnet development panel control
SynapseIndia dotnet development panel controlSynapseIndia dotnet development panel control
SynapseIndia dotnet development panel control
 
SynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client library
 
SynapseIndia php web development
SynapseIndia php web developmentSynapseIndia php web development
SynapseIndia php web development
 
SynapseIndia mobile apps architecture
SynapseIndia mobile apps architectureSynapseIndia mobile apps architecture
SynapseIndia mobile apps architecture
 
SynapseIndia mobile apps deployment framework architecture
SynapseIndia mobile apps deployment framework architectureSynapseIndia mobile apps deployment framework architecture
SynapseIndia mobile apps deployment framework architecture
 
SynapseIndia mobile apps
SynapseIndia mobile appsSynapseIndia mobile apps
SynapseIndia mobile apps
 
SynapseIndia dotnet development
SynapseIndia dotnet developmentSynapseIndia dotnet development
SynapseIndia dotnet development
 
SynapseIndia dotnet client library Development
SynapseIndia dotnet client library DevelopmentSynapseIndia dotnet client library Development
SynapseIndia dotnet client library Development
 
SynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically developmentSynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically development
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Synapseindia strcture of dotnet development part 2

  • 1. Returning values from methods A method which has a non-void return type MUST return a value The return value's type must match the type defined in the method's signature. A void method can use a return statement (with no return value) to exit the method. The return value can be used the same as any other expression. public class Car { private int currentGear; private int currentRpms; public int calculateSpeed() { return currentRpms * currentGear; } }
  • 2. Classes as types When a class is defined, the compiler regards the class as a new type. When a variable is declared, its type can be a primitive type or "Class" type. Any variable whose type is a class is an object reference. The variable is a reference to an instance of the specified class. The variables holds the address (in memory) of the object. int x; 0 Employee anEmployee; null Note: null means “refers to no object”
  • 3. null References null means “refers to no object" Object references can be compared to null to see if an object is present or not. null is the default value of an object reference before it is initialized Employee anEmployee; [...] if (anEmployee == null) { }
  • 4. Initializing Object References - new To initialize an object reference, you must assign it the address of an object The new operator creates a new instance and returns the address of the newly created object new allocates memory for the object new also invokes a method on the object called a constructor new returns the address of the memory allocated for the object. Employee anEmployee; [...] anEmployee = new Employee();
  • 5. Assigning Object References Assigning one reference to another results in two references to the same object If two references contain the same memory address, they are referring to the same object. Remember testing for equality of Strings using == Each object has a reference count When an object's reference count becomes zero, it will be collected by the garbage collector Employee anEmployee = new Employee(); Employee anotherEmployee = anEmployee; Employee anEmployee anotherEmployee
  • 6. Invoking Instance Methods To invoke a method on an object, use the . (dot) operator objectReference.methodName(parameters); • If there is a return value, it can be used as an expression Car aCar = new Car(); [...] if (aCar.calculateSpeed()>110) { System.out.println("You're Speeding!"); } [...]
  • 7. Passing Parameters to Methods Method parameters are declared in the method's signature. When a method invocation is made, any parameters included in the invocation are passed to the method All parameters are passed by value. Ie, a copy is made The value of fundamental data types are copied The value of object references (ie memory addresses) are copied • Parameters become variables within the method. They are not known outside the method. public float calculateInterestForMonth(float rate) { return lowBalanceForMonth * (rate/12.0); }
  • 8. Overloading Methods Java allows for method overloading. A Method is overloaded when the class provides several implementations of the same method, but with different parameters The methods have the same name The methods have differing numbers of parameters or different types of parameters The return type MUST be the same public float calculateInterestForMonth() { return lowBalanceForMonth * (defaultRate/12.0); } public float calculateInterestForMonth(float rate) { return lowBalanceForMonth * (rate/12.0); }
  • 9. Accessor Methods - gets Objects have variables. Because of encapsulation, those variables are generally private However, the outside world may need to use those variables The class implementor may choose to add a "get" method to return the value The usual name of the get method is the name of the variable prefixed with the word "get" getName(), getAddress(), getPhone(), getBalance() public class BankAccount { private float balance; public float getBalance() { return balance; }
  • 10. Accessor Methods - sets Similarly, the outside world may need to set the value of an instance variable The class implementor may choose to implement a set method. The responsibility of the set method is to set the appropriate variable WHILST MAINTAINING data integrity of the object. The usual name of the set method is the name of the variable prefixed with the word "set" setName(), setAddress(), setPhone(), setBalance() public class BankAccount { private String ownerName; public void setOwnerName(String aName) { ownerName = aName; }
  • 11. Design Issues - When to provide gets and sets Get and set often provide confusion for novice programmers Do all instance variables have them? If so, why don't we make the instance variables public and access them directly? Don't gets and sets violate encapsulation? Whether a variable has an associated get and set method is a design issue; it is not a coding issue. Imagine a BankAccount Class All Bank Accounts have Account Numbers Once an Account's Account Number has been set, should it be changeable? • If we don't provide a set method, how do we initialize the variable in the first place?
  • 12. Initializing Objects - Constructors When an object is created, all instance variables are initialized to the default value for their type Fundamentals are 0, 0.0, '000' or false Object references are null In order to put the object into a usable state, its instance variables should be initialized to usable values This could be accomplished by calling the various set methods This is not always possible because it is not required that all instance variables have set methods. Java provides for another method of initializing objects When an object is created, a constructor is invoked. The responsibility of the constructor method is to initialize the object into a usable state.
  • 13. Constructors Constructors have the following characteristics There is NO return type. NOT even void The method name is the same name as the class Constructors can be overloaded In order to put the object into a usable state, its instance variables should be initialized to usable values This could be accomplished by calling the various set methods This is not always possible because it is not required that all instance variables have set methods. Java provides for another method of initializing objects When an object is created (using new), a constructor is invoked. The responsibility of the constructor method is to initialize the object into a usable state.
  • 14. Constructors - Example public class BankAccount { String ownersName; int accountNumber; float balance; public BankAccount() { } public BankAccount(int anAccountNumber) { accountNumber = anAccountNumber; } public BankAccount(int anAccountNumber, String aName) { accountNumber = anAccountNumber; ownersName = aName; } [...] }
  • 15. Constructors - Example When an object is created (using new) the compiler determines which constructor is to be invoked by the parameters passed Multiple constructors allows the class programmer to define many different ways of creating an object. public static void main(String[] args) { BankAccount anAccount = new BankAccount(); BankAccount anotherAccount = new BankAccount(12345); BankAccount myAccount = new BankAccount(33423, "Craig"); }
  • 16. Constructors If no constructors are defined for a class, the compiler automatically generates a default, no argument constructor All instance variables are initialized to default values. However, if any constructor is defined which takes parameters, the compiler will NOT generate the default, no argument constructor If you still need one, you have to explicitly define one.
  • 17. Review What is the difference between classes and objects? What are the modifiers for classes, instance variables and methods? What do they mean? What is encapsulation? Why is it important? How are method parameters defined? How are method parameters passed? How do accessor methods support encapsulation? What are constructors?