This chapter reviews method parameters and local variables, as well as method overloading and method signature.
Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters. When a method is called, the corresponding method is invoked by matching the arguments in the call to the parameter lists of the methods. The name together with the number and types of a method's parameter list is called the signature of a method. The return type itself is not part of the signature of a method.
14. Two Objects
Answer:
Mystery sum: 40
sum: 99
Two Objects
Colors in the following show how this works. this
is used in the constructor where the instance variable, not the parameter, should be used.
class Mystery
{
private int sum;
public Mystery( int sum )
{
this.sum = sum;
}
public void increment( int inc )
{
sum = sum + inc;
System.out.println("Mystery sum: " + sum );
}
}
public class Tester
{
public static void main ( String[] args)
{
int sum = 99;
Mystery myst = new Mystery( 34 );
myst.increment( 6 );
System.out.println("sum: " + sum );
}
}
Now look at this modified version:
class Mystery
{
private int sum;
public Mystery( int x )
{
sum = x;
}
public void increment( int inc )
{
sum = sum + inc;
System.out.println("Mystery sum: " + sum );
}
}
public class Tester
{
public static void main ( String[] args)
{
Mystery mystA = new Mystery( 34 );
Mystery mystB = new Mystery( 13 );
mystA.increment( 6 );
mystB.increment( 7 );
}
}
Question 14:
Now what is printed?