COMP-202: Foundations of Programming Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015
Announcements Assignment 3: Due on 14 th of June at 11:30 pm. Midterm grades are published on MyCourses. Class Average is 75.55 %. Midterm exam is uploaded on the course website for your reference.
This Lecture Review on static, public and private access specifiers Method Overloading Passing objects to methods One step at a time.
Review: static, public, and private
What is the output? public class Bird { private double height; private double wingspan; private boolean canfly; public Bird (double h, double w, boolean f){ height = h; wingspan = w; canfly = f; public static void main(string [] args){ Bird b1 = new Bird(0.5, 1, true); System.out.println("The Bird data is : Height = "+b1.height+" Wing Span = "+b1.wingspan+" Can Fly? " +b1.canfly);
What is the output? public class Bird { private double height; private double wingspan; public Bird (double height, double wingspan){ height = height; wingspan = wingspan; public static void main(string [] args){ Bird b1 = new Bird(0.5, 1); Ambiguity with the variable names. Need to use this.height to refer to the variable height of the class Bird. System.out.println("The Bird data is : Height = "+b1.height+" Wing Span = "+b1.wingspan);
What is the output? public class Bird { private double height; private double wingspan; private boolean canfly; Static method cannot access non-static variable height. public Bird (double h, double w, boolean f){ height = h; wingspan = w; canfly = f; public static void main(string [] args){ System.out.println("The height is : "+ height);
What is the output? public class Bird { private double height; private double wingspan; private static int numbirds = 0; Static method can access static variable numbirds. So NO ERROR. public Bird (double h, double w){ height = h; wingspan = w; numbirds++; public static void main(string [] args){ System.out.println("The numbirds = "+ numbirds);
static Public Class Student { public int ID; public String Name; public String Grade; public static int numstudents = 0; numstudents static variable is shared by all the objects. 4 Objects : ID: Name: Grade: 435678271 Sarah A- ID: Name: Grade: 435645231 Bob B- ID: Name: Grade: 435932949 San F ID: Name: Grade: 435321234 Nat A
The variable height is private to the class its defined in (Bird). Cannot be accessed from other classes. public class Bird { private double height; private double wingspan; private static int numbirds = 0; public Bird (double h, double w){ height = h; wingspan = w; numbirds++; public class testbird{ public static void main(string[] str){ Bird b1 = new Bird(0.4,1.5); System.out.println("The Bird data is : Height = "+b1.height);
Changing height to public makes it accessible from outside classes. public class Bird { public double height; private double wingspan; private static int numbirds = 0; public Bird (double h, double w){ height = h; wingspan = w; numbirds++; public class testbird{ public static void main(string[] str){ Bird b1 = new Bird(0.4,1.5); System.out.println("The Bird data is : Height = "+b1.height);
Method Overloading
Same name, Different behavior CALL
Same name, Different behavior Compute Area Rectangle Area = l * b Circle Area = Triangle Area =
In Java We have already seen such behavior in Java!!! System.out.println(3); // int System.out.println('3'); // char System.out.println("3"); // String int[] intarr = {1, 2, 3; System.out.println(intarr); // prints memory address System.out.println(true); // boolean
Method Overloading You're allowed to have different methods with the same name, as long as they have different signatures. Signature = method name + parameter list (with types) So, as long as the methods require different parameter types, you're fine.
Okay: Examples public void dosomething(int val) { public void dosomething(int val, double val2) { public void dosomething(string val) { public void dosomething(double val, int val2) { Not okay (given above): Just having different returntypes does not qualify as different method signature. public String dosomething(int val) { public void dosomething(int otherval) {
Example public class overload{ public static void main(string [] str){ System.out.println("Area of this circle = "+computearea(5)); System.out.println("Area of this circle = "+computearea(5,3)); public static double computearea(double r){ return Math.PI*r*r; public static double computearea(double l, double b){ return l*b;
Bad Idea There's nothing to stop you from having an overloaded method, where each version does something completely unrelated. public void dosomething(int val) { System.out.println(val); public String dosomething(double val) { return "" + val;
Overloading the Constructor public class Employee { private int id; private String name; private double salary; public Employee() { System.out.println("In Constructor 1"); id = 0; name = " "; salary = 0; Contd.. public Employee(int x) { System.out.println("In Constructor 2"); id = x; public Employee(String str) { System.out.println("In Constructor 3"); name = str; public static void main(string [] str) { Employee e1 = new Employee(); Employee e2 = new Employee(101); Employee e3 = new Employee("Bob");
Let us Try it out!! Write a Cat class. It should: have two fields, for the name and the age have two possible constructors (overloaded). Both of them requires the name of the cat. One of them creates a kitten with default age 0.0; the other creates a cat of a specified age. have a meow() method. If the cat has age < 1.0, this method prints "<name> mews". Otherwise, it prints "<name> meows". a birthday() method that increments age by 1.0 Write code to test this class as well.
Objects Are Reference Types Primitive types: float, int, double, boolean, char, long, short, byte Variables of primitive types store the actual value Reference types: arrays, every other type Variables store an address to the actual value in memory.
Declaring Object Variables Variable declaration: Cat c1; No new Cat object is created. Only a place to store a memory address of a Cat object. c1 Can take the address of Cat object
Creating the Object in Memory This happens with the new keyword. Cat c1; c1 = new Cat ( Kitty"); Picture in your mind: @1100 @1100 c1.name Kitty".age 0.0
Variable Assignment Cat c1 = new Cat( Kitty"); Cat c2 = c1; @1100 @1100 c1 @1100.name Kitty".age 0.0 c2
Variable Assignment @1100 Cat c1 = new Cat( Kitty"); Cat c2 = c1; c2 = new Cat("Whiskers", 3.0); @1100 c1.name Kitty".age 0.0 @1500 @1500 @1100 c2.name "Whiskers".age 3.0
Variable Assignment Cat c1 = new Cat( Kitty"); Cat c2 = c1; c2 = new Cat("Whiskers", 3.0); c2 = c1; @1100 c1 @1100.name Kitty".age 0.0 @1500 @1500 @1100 c2 Nothing refers to Whiskers any more!.name "Whiskers".age 3.0
Garbage Collection At some point, Java will notice and will perform garbage collection to free up that memory. @1100 @1100 c1 @1100 c2.name Kitty".age 0.0
Aliases Can change an object from any of its references: c1.birthday(); (OR c2.birthday()); @1100 @1100 c1 @1100 c2.name Kitty".age 1.0 c1 and c2 are known as aliases of each other. They point to the same place in memory.
Comparisons Using == to compare reference types means you are comparing their memory addresses. You need to write your own.equals() method for a class if you want to compare their values. e.g., c1 == c2 true, because they point to the same place in memory If I create another Cat called Kitty" with the same age and put it into a variable called c3, c1 == c3 will be false
You can use null to mean that a reference type is referring to nothing. (This is sometimes useful.) c1 = null; null null @1100 c1 @1100.name Kitty".age 1.0 c2
Checking for null You can check if a reference type is pointing to nothing using ==. if (c1 == null) { c1 = new Cat("Paws", 0.6);
Passing Reference Types Recall: Parameter passing works just like an assignment statement. The value of the actual parameter (the value when calling the method) is copied into the method's formal parameter (the variable name in the method). This means when passing reference types, we are copying the address to the object.
Example public static void agecat(cat cat) { // this changes the value pointed to by cat cat.birthday(); In the main method: Cat c = new Cat("Harvey", 0.4); agecat(c); // Harvey is now 1.4 years old.
Example 2 public static void replacecat(cat cat) { cat = new Cat("AngryCat", 2.0); In the main method: Cat c = new Cat("Harvey", 0.4); replacecat(c); // c still points to Harvey
Try it out!! Write a.equals(cat) method for the Cat class that returns true if and only if both cats have the same name and age.
Try it out!! Write a CatRescue class: 1. Stores an array of Cats waiting to be adopted. 2. Takes an int in its constructor to represent the capacity of the cat rescue shelter. 3. Has an addcat(cat) method which adds a cat to the shelter (i.e., adds it to the next available spot in the array). Returns true if successful. If shelter is full, don't do anything and return false. 4. Has an adopt() method which returns the oldest cat in the shelter, removing it from the shelter.
Summary Method Overloading Objects are References Passing Objects into Methods