Lab 9

CS203
Spring 2013
Apr 5

Goals

  • Experiment with types and subtypes

Activities

  1. Launch Netbeans, and create a new project named lab9 under your cs203 course directory
    • make the main class Examples rather than the default
  2. Add the tester.jar file to your project’s Libraries
  3. 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...");
        }
    }

  4. 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)

  5. 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.
  6. 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!
courses/cs203-201301/labs/lab9.txt · Last modified: 2013/04/01 01:11 by mlsmith
VCCS Top Events Extended Site Search Login Vassar Science Web Vassar Home Driven by DokuWiki Valid XHTML 1.0