====== Lab 9 ======
~~NOTOC~~
** CS203 ** \\
** Spring 2013 ** \\
** Apr 5 **
===== Goals =====
* Experiment with types and subtypes
===== Activities =====
- Launch Netbeans, and create a new project named **//lab9//** under your ''cs203'' course directory
* make the main class ''Examples'' rather than the default
- Add the ''tester.jar'' file to your project's Libraries
- Add an ''A'' class and a ''B'' class to your project, and copy/paste the respective code below:
/**
* cs203
* Spring 2013
* Lab 9
*
* file: B.java
*/
public class B {
public void bmethod1() {
System.out.println("class B: bmethod1() called...");
}
public void bmethod2() {
System.out.println("class B: bmethod2() called, calling which class's bmethod1?...");
bmethod1();
}
}
/**
* cs203
* Spring 2013
* Lab 9
*
* file: A.java
*/
public class A extends B {
@Override
public void bmethod1() {
System.out.println("class A: bmethod1() called...");
}
}
- Add code to the ''main()'' method in your ''Examples'' class to experiment with classes ''A'' and ''B''. Your code should generate the following output when run:
run:
Initializing myB, an object of type B, to an instance of type B...
class B: bmethod1() called...
class B: bmethod2() called, which class's bmethod1() will I call???
class B: bmethod1() called...
Initializing myB, and object of type B, to an instance of type A...
class A: bmethod1() called...
class B: bmethod2() called, which class's bmethod1() will I call???
class A: bmethod1() called...
BUILD SUCCESSFUL (total time: 0 seconds)
- Notice how this is a way to exploit the behavior of B type objects. Malicious coders could potentially do bad things in class A's ''bmethod1''.
- One way to protect the behavior of B objects is to make class B final:
public final class B {
Make class B final and observe what happens when you try to compile your code. Discuss with Marc or one of our coaches.
===== Submit your lab =====
* When you've had enough fun, submit your work using the submit203 script: \\ ''submit203 lab9 lab9''
===== When you've had enough (for today) =====
* Logout and have a good weekend!