Wednesday, January 31, 2007

Notes from Week #3

Themes:
  1. Beware: local vs. global
  2. Overiding: which method is called?
  3. Overloading: which method is called?
  4. Static variables
  5. Recursion (we didn't get to this topic this time)

Example 1:

How big will you see the sun?

public class BigSun extends wheels.users.Frame {

private wheels.users.Ellipse e;
private int bigSize;

public BigSun() {
int bigSize = 200;

e = new wheels.users.Ellipse();
}

public void makeBig() {
e.setSize(bigSize, bigSize);
}

public static void main(String[] args) {
BigSun sun = new BigSun();
sun.makeBig();
}

}

Example 2:
What is wrong here? How to make it right? What does the output look like? What if we change changeSize in BlueSun to changeSize2 ?

import wheels.users.*;

public class Sun extends Frame {

private Ellipse e;

public Sun() {
e = new Ellipse();
}

public void changeSize() {
e.setSize(3,3);
}

}
----
import java.awt.Color;

public class BlueSun extends Sun {

public BlueSun() {
super();
e.setColor(Color.BLUE);
}

public void changeSize() {
e.setSize(200, 200);
}

public static void main(String[] args) {
BlueSun sun = new BlueSun();
sun.changeSize();
}

}

Example 3:
What is the output?

public class TestOverload {

private static int f(int x) {
return x*x;
}

private static int f(int[] a) {
return f(a[0]) + f(a[1]) + f(a[2]);
}

public static void main(String[] args) {
int x = 7;
int a[] = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;

System.out.println("The 1st result is " + f(x));
System.out.println("The 2nd result is " + f(a));
}

}

Example 4:
import java.awt.Color;

import wheels.users.*;

public class UglyAlien extends Ellipse {

private static Ellipse eye;

public UglyAlien() {
this.setSize(100, 100);
eye = new Ellipse();
eye.setFillColor(Color.WHITE);
eye.setSize(20, 20);
}

public void moveTo(int x, int y) {
this.setLocation(x, y);
eye.setLocation(x+40, y+40);
}

public void wink() {
eye.setSize(20, 5);
}
}

import wheels.users.*;

public class UglyAlienApp extends Frame{

public UglyAlienApp() {
UglyAlien a1, a2;

a1 = new UglyAlien();
a2 = new UglyAlien();

a1.moveTo(0, 0);
a2.moveTo(100, 0);

a2.wink();
}

public static void main(String[] args) {
new UglyAlienApp();
}

}


Note: the code on this post is badly commented. It's because of the blogger's thing... I'm too lazy to fix it. Do not follow this style. You should always indent your code nicely.

No comments:

Contributors