Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
COMP-202: Foundations of Programming
Lecture 10: Method Overloading and
Passing Objects to Methods.
Sandeep Manjanna, Summer 2015
Announcements
• Assignment 3: Due on 14th 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);
System.out.println("The Bird data is : Height = "+b1.height+"
Wing Span = "+b1.wingSpan);
}
}
Ambiguity with the variable
names. Need to use this.height
to refer to the variable height
of the class Bird.
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){
System.out.println("The height is : "+ height);
}
}
Static method cannot access
non-static variable height.
What is the output?
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 static void main(String [] args){
System.out.println("The numBirds = "+ numBirds);
}
}
Static method can access
static variable numBirds.
So NO ERROR.
static
435678271ID:
SarahName:
A-Grade:
435645231ID:
BobName:
B-Grade:
435932949ID:
SanName:
FGrade:
435321234ID:
NatName:
AGrade:
4 Objects :
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.
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);
}
}
The variable height is private
to the class its defined in
(Bird). Cannot be accessed
from other 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);
}
}
Changing height to public
makes it accessible from
outside classes.
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.
ExamplesOkay:
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):
public String doSomething(int val) {
public void doSomething(int otherVal) {
Just having different return-
types does not qualify as
different method signature.
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 Constructorpublic class Employee
{
private int id;
private String name;
private double salary;
public Employee()
{
System.out.println("In Constructor 1");
id = 0;
name = " ";
salary = 0;
}
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");
}
}
Contd..
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 typeVariables 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:
c1
.name “Kitty"
.age 0.0
@1100
@1100
c2
@1100
c1
@1100
Variable Assignment
Cat c1 = new Cat(“Kitty");
Cat c2 = c1;
.name “Kitty"
.age 0.0
@1100
@1100
Variable Assignment
Cat c1 = new Cat(“Kitty");
Cat c2 = c1;
c2 = new Cat("Whiskers", 3.0);
.name "Whiskers"
.age 3.0
.name “Kitty"
.age 0.0
c2
@1500
c1
@1100
@1100
@1500
Variable Assignment
Cat c1 = new Cat(“Kitty");
Cat c2 = c1;
c2 = new Cat("Whiskers", 3.0);
c2 = c1;
.name "Whiskers"
.age 3.0
.name “Kitty"
.age 0.0
c2
c1
@1100
@1100
@1500
Nothing refers to
Whiskers any
more!
@1500@1100
At some point, Java will notice and will perform garbage collection to free up that memory.
.name “Kitty"
.age 0.0
c2
@1100
c1
@1100
@1100
Garbage Collection
Can change an object from any of its references:
c1.birthday();
(OR c2.birthday());
.name “Kitty"
.age 1.0
c2
@1100
c1
@1100
@1100
Aliases
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;
.name “Kitty"
.age 1.0
c2
@1100
c1
null
@1100
null
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 2public 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