SlideShare a Scribd company logo
1 of 29
Download to read offline
Writing your own class
Phase 2
▪ Objects interacting with other objects
▪ Passing objects to methods
▪ Objects as attributes
Using Objects
Passing objects as parameters to a method.
▪ We know that we can pass primitive variables (int,
float, boolean…) to methods.
▪ What about treating objects as we treat ordinary,
primitive variables? Can we pass objects as arguments
to methods?
float addTwoNumbers(float x, float y) {
return x+y;
}
Using Objects
Returning an object from a method:
▪ We also know that we can return primitive values (int,
float, boolean…) from methods.
▪ What about treating objects as we treat ordinary,
primitive variables? Can we return objects from methods?
float addTwoNumbers(float x, float y) {
return x+y;
}
Using Objects
We can use objects as attributes.
▪ e.g. Equipment that can be loaned out to a student.
Exercise: Create a new Equipment class
Attributes
‒ name
‒ value
‒ Student to whom the equipment
is loaned
Methods
‒ get methods for name and value
‒ Loan equipment to student
• See which student this
equipment is loaned to
• Constructor: set name and value
• Note that because name and value do not change, we can
assigned them at creation and then not give them set
methods.
Using Objects
Attributes
• name
• value
• Student to whom the equipment is loaned
private String name;
private float value;
private Student LoanedTo;
Using Objects
public Equipment(String newName, float val) {
name = newName;
value = val;
}
Methods
• Constructor: set name and value
• Get methods for name and value
• Loan equipment to student
• See which student this equipment is loaned to
Using Objects
public String getName() {return name;}
public float getValue() {return value;}
Methods
• Constructor: set name and value
• Get methods for name and value
• Loan equipment to student
• See which student this equipment is loaned to
Using Objects
Methods
• Constructor: set name and value
• Get methods for name and value
• Loan equipment to student
• See which student this equipment is loaned to
public void loan(Student s) {LoanedTo = s;}
Using Objects
Methods
• Constructor: set name and value
• Get methods for name and value
• Loan equipment to student
• See which student this equipment is loaned to
public Student getLoanedTo() {return LoanedTo;}
Using Objects
public Equipment(String newName, float val) {
name = newName;
value = val;
}
public String getName() {return name;}
public float getValue() {return value;}
public void loan(Student s) {LoanedTo = s;}
public Student getLoanedTo() {return LoanedTo;}
Methods
• Constructor: set name and value
• Get methods for name and value
• Loan equipment to student
• See which student this equipment is loaned to
Using Objects
public class Equipment {
private String name;
private Student LoanedTo;
private float value;
public Equipment(String newName, float val) {
name = newName;
value = val;
}
public String getName() {return name;}
public float getValue() {return value;}
public void loan(Student s) {LoanedTo = s;}
public Student getLoanedTo() {return LoanedTo;}
}
Writing your own class
▪ We can add an BorrowedEquipment attribute to the
Student class, to record if they borrow any equipment:
public class Student {
...
private Equipment BorrowedEquipment;
...
void BorrowEquip(Equipment newEquip) {BorrowedEquipment =
newEquip;}
Equipment getBorrowedEquipment() {return BorrowedEquipment;}
void returnEquip() {BorrowedEquipment = null;}
Writing your own class
Summary so far
▪ We can create another class, called Equipment
▪ Equipment has an attribute Student
▪ Equipment has a method that takes Student as an
argument
▪ Let’s now use these classes
Using Objects
▪ In this code, we create a Student object and two
Equipment objects, we loan those equipment objects to
the same student.
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
Equipment e1 = new Equipment("Multimeter", 149.99f);
Equipment e2 = new Equipment("Oscilloscope", 3499.99f);
e1.loan(s);
e2.loan(s);
}
}
Using Objects
▪ Recall: for an object, the identifier is actually a pointer
(address) to the object
▪ When we pass an object to a method, we are not
passing the actual object – we are passing a reference
to the object to that method.
Creating and returning objects
Creating and returning an object from a method:
▪ We know methods of objects can return objects
▪ Also, methods of objects can also create objects and
return them.
▪ This might be helpful if we want to create an object
based on the current object.
▪ Example: we want to give someone else all the marks
for all the tests, but anonymously i.e. without a name.
▪ We don’t want to change our original object, so we
return a new object with the name removed.
Creating and returning objects
▪ Create a new
Student object with
a blank name
▪ Copy the test marks
across
▪ Return the new
object (remember,
returning a
pointer…)
Student Anonymise() {
Student s_anon = new Student("","");
for (int i = 0; i < testMarks.length; i++)
s_anon.testMarks[i] = testMarks[i];
return s_anon;
}
Notice:
▪ What is being returned?
▪ What type is being returned?
Creating and returning objects
▪ Now to actually use this:
▪ s.Anonymise() creates a Student object, does some stuff to it and
then returns a pointer to that object.
Student s = new Student("Jonathan", "Parker");
s.setTestMark(75f, 0);
s.setTestMark(55f, 1);
s.setTestMark(80f, 2);
s.setTestMark(93.5f, 3);
s.setTestMark(82.5f, 4);
Student s2 = s.Anonymise();
Local variables
Local variables:
▪ Variables that live inside a method
▪ Not visible to other methods, even in the same class or object.
▪ Avoid using the same name as other attributes in the class or
object.
this keyword
this keyword
▪ There is possible ambiguity between passed variables and
instance variables.
public class Student {
private String firstName;
private String lastName;
//...
void changeName(String firstName, String lastName) {
//Inside this method, what does firstName refer to?
//The class attribute or the first argument?
}
?
?
this keyword
this keyword
▪ What if I declare a local variable to have the same name as an
attribute? Which one is used?
public class Student {
private String firstName;
private String lastName;
//...
void anotherMethod() {
String firstName = "H";
return firstName;
}
?
?
this keyword
this keyword
▪ The local variable (the passed variable is treated as a local
variable) will be used, not the attribute.
▪ To overcome this, we can use the this keyword to make it
clear we are referring to the attribute.
▪ this is a pointer to the current object.
this keyword
this keyword
private String firstName;
private String lastName;
void changeName(String firstName, String lastName) {
{*firstName and lastName refer to the local variable.
this.firstName and this.lastName refer to the instance
variable. *}
this.firstName = firstName;
this.lastName = lastName;
}
Overloading
▪ Overloaded functions are distinguished by their method
signature (types of input parameters)
▪ When we use them, the correct overloaded function will be
chosen on the basis of the type of input parameters.
▪ It is very common to overload constructor methods
▪ Recall constructors are simply methods that are run when the
object is created
Overloading
The use of the same method name for different functions.
Overloading
▪ Before:
▪ Example: Now, lets have the option of creating a Student
object and not requiring the user to enter a name.
Student(String defaultFirstName, String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
testMarks = new float[5];
}
Student s = new Student("Jonathan", "Parker");
Overloading
▪ Example: Lets have the option of creating a Student object and
not requiring the user to enter a name.
▪ Now add:
Student s = new Student();
Student(){
firstName = "John";
lastName = "Smith";
testMarks = new float[5];
}
Different input arguments!
Overloading
▪ Example: Lets have the option of creating a Student object and
allowing them to enter the number of tests.
▪ Add even more:
Student s = new Student("Jonathan", "Parker", 10);
Student(String defaultFirstName, String defaultLastName, int NoTests){
firstName = defaultFirstName;
lastName = defaultLastName;
testMarks = new float[NoTests];
}
Overloading
▪ For overloaded functions, it will look for the method that
matches the input arguments (method signature) and run
that method. Example:
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
...
Student(String defaultFirstName, String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
testMarks = new float[5];
}
will call:
Two strings
Two strings
Overloading
▪ For overloaded functions, it will look for the method that
matches the input arguments (method signature) and run
that method. Example:
public class L4 {
public static void main(String[] args) {
Student s = new Student();
...
Student(){
firstName = "John";
lastName = "Smith";
testMarks = new float[5];
}
will call:
No arguments
No arguments

More Related Content

Similar to Lecture 4 part 2.pdf

Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 

Similar to Lecture 4 part 2.pdf (20)

38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptx
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)Basic object oriented concepts (1)
Basic object oriented concepts (1)
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
OOPS
OOPSOOPS
OOPS
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Object concepts
Object conceptsObject concepts
Object concepts
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
 
Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 

More from SakhilejasonMsibi (10)

Lecture 6.pdf
Lecture 6.pdfLecture 6.pdf
Lecture 6.pdf
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Lecture2.pdf
Lecture2.pdfLecture2.pdf
Lecture2.pdf
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
 
Lecture 7.pdf
Lecture 7.pdfLecture 7.pdf
Lecture 7.pdf
 
Lecture 5.pdf
Lecture 5.pdfLecture 5.pdf
Lecture 5.pdf
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Lecture 9.pdf
Lecture 9.pdfLecture 9.pdf
Lecture 9.pdf
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
 

Recently uploaded

Online crime reporting system project.pdf
Online crime reporting system project.pdfOnline crime reporting system project.pdf
Online crime reporting system project.pdf
Kamal Acharya
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
rahulmanepalli02
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
benjamincojr
 

Recently uploaded (20)

Online crime reporting system project.pdf
Online crime reporting system project.pdfOnline crime reporting system project.pdf
Online crime reporting system project.pdf
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 
Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdf
 
Piping and instrumentation diagram p.pdf
Piping and instrumentation diagram p.pdfPiping and instrumentation diagram p.pdf
Piping and instrumentation diagram p.pdf
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
Artificial Intelligence in due diligence
Artificial Intelligence in due diligenceArtificial Intelligence in due diligence
Artificial Intelligence in due diligence
 
"United Nations Park" Site Visit Report.
"United Nations Park" Site  Visit Report."United Nations Park" Site  Visit Report.
"United Nations Park" Site Visit Report.
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
 
What is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsWhat is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, Functions
 
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message QueuesLinux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
 
Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptx
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
 
handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailing
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
Dynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxDynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptx
 

Lecture 4 part 2.pdf

  • 1. Writing your own class Phase 2 ▪ Objects interacting with other objects ▪ Passing objects to methods ▪ Objects as attributes
  • 2. Using Objects Passing objects as parameters to a method. ▪ We know that we can pass primitive variables (int, float, boolean…) to methods. ▪ What about treating objects as we treat ordinary, primitive variables? Can we pass objects as arguments to methods? float addTwoNumbers(float x, float y) { return x+y; }
  • 3. Using Objects Returning an object from a method: ▪ We also know that we can return primitive values (int, float, boolean…) from methods. ▪ What about treating objects as we treat ordinary, primitive variables? Can we return objects from methods? float addTwoNumbers(float x, float y) { return x+y; }
  • 4. Using Objects We can use objects as attributes. ▪ e.g. Equipment that can be loaned out to a student. Exercise: Create a new Equipment class Attributes ‒ name ‒ value ‒ Student to whom the equipment is loaned Methods ‒ get methods for name and value ‒ Loan equipment to student • See which student this equipment is loaned to • Constructor: set name and value • Note that because name and value do not change, we can assigned them at creation and then not give them set methods.
  • 5. Using Objects Attributes • name • value • Student to whom the equipment is loaned private String name; private float value; private Student LoanedTo;
  • 6. Using Objects public Equipment(String newName, float val) { name = newName; value = val; } Methods • Constructor: set name and value • Get methods for name and value • Loan equipment to student • See which student this equipment is loaned to
  • 7. Using Objects public String getName() {return name;} public float getValue() {return value;} Methods • Constructor: set name and value • Get methods for name and value • Loan equipment to student • See which student this equipment is loaned to
  • 8. Using Objects Methods • Constructor: set name and value • Get methods for name and value • Loan equipment to student • See which student this equipment is loaned to public void loan(Student s) {LoanedTo = s;}
  • 9. Using Objects Methods • Constructor: set name and value • Get methods for name and value • Loan equipment to student • See which student this equipment is loaned to public Student getLoanedTo() {return LoanedTo;}
  • 10. Using Objects public Equipment(String newName, float val) { name = newName; value = val; } public String getName() {return name;} public float getValue() {return value;} public void loan(Student s) {LoanedTo = s;} public Student getLoanedTo() {return LoanedTo;} Methods • Constructor: set name and value • Get methods for name and value • Loan equipment to student • See which student this equipment is loaned to
  • 11. Using Objects public class Equipment { private String name; private Student LoanedTo; private float value; public Equipment(String newName, float val) { name = newName; value = val; } public String getName() {return name;} public float getValue() {return value;} public void loan(Student s) {LoanedTo = s;} public Student getLoanedTo() {return LoanedTo;} }
  • 12. Writing your own class ▪ We can add an BorrowedEquipment attribute to the Student class, to record if they borrow any equipment: public class Student { ... private Equipment BorrowedEquipment; ... void BorrowEquip(Equipment newEquip) {BorrowedEquipment = newEquip;} Equipment getBorrowedEquipment() {return BorrowedEquipment;} void returnEquip() {BorrowedEquipment = null;}
  • 13. Writing your own class Summary so far ▪ We can create another class, called Equipment ▪ Equipment has an attribute Student ▪ Equipment has a method that takes Student as an argument ▪ Let’s now use these classes
  • 14. Using Objects ▪ In this code, we create a Student object and two Equipment objects, we loan those equipment objects to the same student. public class L4 { public static void main(String[] args) { Student s = new Student("Jonathan", "Parker"); Equipment e1 = new Equipment("Multimeter", 149.99f); Equipment e2 = new Equipment("Oscilloscope", 3499.99f); e1.loan(s); e2.loan(s); } }
  • 15. Using Objects ▪ Recall: for an object, the identifier is actually a pointer (address) to the object ▪ When we pass an object to a method, we are not passing the actual object – we are passing a reference to the object to that method.
  • 16. Creating and returning objects Creating and returning an object from a method: ▪ We know methods of objects can return objects ▪ Also, methods of objects can also create objects and return them. ▪ This might be helpful if we want to create an object based on the current object. ▪ Example: we want to give someone else all the marks for all the tests, but anonymously i.e. without a name. ▪ We don’t want to change our original object, so we return a new object with the name removed.
  • 17. Creating and returning objects ▪ Create a new Student object with a blank name ▪ Copy the test marks across ▪ Return the new object (remember, returning a pointer…) Student Anonymise() { Student s_anon = new Student("",""); for (int i = 0; i < testMarks.length; i++) s_anon.testMarks[i] = testMarks[i]; return s_anon; } Notice: ▪ What is being returned? ▪ What type is being returned?
  • 18. Creating and returning objects ▪ Now to actually use this: ▪ s.Anonymise() creates a Student object, does some stuff to it and then returns a pointer to that object. Student s = new Student("Jonathan", "Parker"); s.setTestMark(75f, 0); s.setTestMark(55f, 1); s.setTestMark(80f, 2); s.setTestMark(93.5f, 3); s.setTestMark(82.5f, 4); Student s2 = s.Anonymise();
  • 19. Local variables Local variables: ▪ Variables that live inside a method ▪ Not visible to other methods, even in the same class or object. ▪ Avoid using the same name as other attributes in the class or object.
  • 20. this keyword this keyword ▪ There is possible ambiguity between passed variables and instance variables. public class Student { private String firstName; private String lastName; //... void changeName(String firstName, String lastName) { //Inside this method, what does firstName refer to? //The class attribute or the first argument? } ? ?
  • 21. this keyword this keyword ▪ What if I declare a local variable to have the same name as an attribute? Which one is used? public class Student { private String firstName; private String lastName; //... void anotherMethod() { String firstName = "H"; return firstName; } ? ?
  • 22. this keyword this keyword ▪ The local variable (the passed variable is treated as a local variable) will be used, not the attribute. ▪ To overcome this, we can use the this keyword to make it clear we are referring to the attribute. ▪ this is a pointer to the current object.
  • 23. this keyword this keyword private String firstName; private String lastName; void changeName(String firstName, String lastName) { {*firstName and lastName refer to the local variable. this.firstName and this.lastName refer to the instance variable. *} this.firstName = firstName; this.lastName = lastName; }
  • 24. Overloading ▪ Overloaded functions are distinguished by their method signature (types of input parameters) ▪ When we use them, the correct overloaded function will be chosen on the basis of the type of input parameters. ▪ It is very common to overload constructor methods ▪ Recall constructors are simply methods that are run when the object is created Overloading The use of the same method name for different functions.
  • 25. Overloading ▪ Before: ▪ Example: Now, lets have the option of creating a Student object and not requiring the user to enter a name. Student(String defaultFirstName, String defaultLastName){ firstName = defaultFirstName; lastName = defaultLastName; testMarks = new float[5]; } Student s = new Student("Jonathan", "Parker");
  • 26. Overloading ▪ Example: Lets have the option of creating a Student object and not requiring the user to enter a name. ▪ Now add: Student s = new Student(); Student(){ firstName = "John"; lastName = "Smith"; testMarks = new float[5]; } Different input arguments!
  • 27. Overloading ▪ Example: Lets have the option of creating a Student object and allowing them to enter the number of tests. ▪ Add even more: Student s = new Student("Jonathan", "Parker", 10); Student(String defaultFirstName, String defaultLastName, int NoTests){ firstName = defaultFirstName; lastName = defaultLastName; testMarks = new float[NoTests]; }
  • 28. Overloading ▪ For overloaded functions, it will look for the method that matches the input arguments (method signature) and run that method. Example: public class L4 { public static void main(String[] args) { Student s = new Student("Jonathan", "Parker"); ... Student(String defaultFirstName, String defaultLastName){ firstName = defaultFirstName; lastName = defaultLastName; testMarks = new float[5]; } will call: Two strings Two strings
  • 29. Overloading ▪ For overloaded functions, it will look for the method that matches the input arguments (method signature) and run that method. Example: public class L4 { public static void main(String[] args) { Student s = new Student(); ... Student(){ firstName = "John"; lastName = "Smith"; testMarks = new float[5]; } will call: No arguments No arguments