Category Archives: Announcements

Chapter 5: Inner Classes – Nested Classes

January 12th, 2017

Classwork:

Inner Classes – Nested Classes
A class can be declared inside another class. Just as a loop written inside another loop is called a nested loop, a class written inside another class is called a nested class. The nested class is considered a member of the enclosing class, just like a variable or method.

  • Just like any other class, a nested class produces a separate bytecode file.
  • The name of the bytecode file is the name of the enclosing class followed by the $ character followed by the name of the nested class.
  • Like any other bytecode file, it has an extension of .class. A class called Nested that is declared inside a class called Enclosing will result in a compiled bytecode file called Enclosing$Nested.class.
  • Because it is a member of the enclosing class, a nested class has access to the enclosing class’s instance variables and methods, even if they are declared with private visibility.
  • The enclosing class can directly access data in the nested class only if the data is declared public.
  • Data should always be kept private to follow the rules of encapsulation. However, the exception applies to nested class so the enclosing class can get to the data.
  • Such a privileged relationship should be reserved for appropriate situations.
  • The static modifier can be applied to a class, but only if the class is nested inside another.
  • Like static methods, a static nested class cannot reference instance variables or methods defined in its enclosing class.
  • //********************************************************************
    //  TestInner.java       Author: Lewis/Loftus
    //
    //  Demonstrates the access capabilities of inner classes.
    //********************************************************************
       public class TestInner
       {
          //-----------------------------------------------------------------
          //  Creates and manipulates an Outer object.
          //-----------------------------------------------------------------
          public static void main (String[] args)
          {
             Outer out = new Outer();
             System.out.println (out);
             System.out.println();
             out.changeMessages();
             System.out.println (out);
          } 
       }
    

    Output
    Copy these files to your project.
    Show and explain the output on edmodo.com

    
    //********************************************************************
    //  Outer.java       Author: Lewis/Loftus
    //
    //  Represents a class that encapsulates an inner class.
    //********************************************************************
    public class Outer
    {
       private int num;
       private Inner in1, in2;
       //-----------------------------------------------------------------
       //  Sets up this object, initializing one int and two objects
       //  created from the inner class.
       //-----------------------------------------------------------------
       public Outer()
       {
         num = 9876;
         in1 = new Inner ("Half of the problem is 90% mental.");
         in2 = new Inner ("Another deadline. Another miracle.");
       }
       //-----------------------------------------------------------------
       //  Changes the messages in the Inner objects (directly).
       //-----------------------------------------------------------------
       public void changeMessages()
       {
          in1.message = "Life is uncertain. Eat dessert first.";
          in2.message = "One seventh of your life is spent on Mondays.";
       }
       //*****************************************************************
       //  Returns this object                
       //*****************************************************************
    
       public String toString()
       {
          return in1 + "\n" + in2;
       }
    
          //*****************************************************************
          //  Represents an inner class.
          //*****************************************************************
          private class Inner
          {
             public String message;
             //--------------------------------------------------------------
             //  Sets up this Inner object with the specified string.
             //--------------------------------------------------------------
             public Inner (String str)
             {
                message = str;
             }
             //--------------------------------------------------------------
             //  Returns this object as a string, including a value from
             //  the outer class.
             //--------------------------------------------------------------
             public String toString()
             {
                num++;
                return message + "\nOuter num = " + num;
             }
           }
       }
        
    
  • Each Inner object contains a public String called message.
  • Because it is public, the changeMessages of the Outer class can reach in and modify the contents.
  • As the authors’ve stressed many times, giving data public access should be avoided in general. However, in this case, since Inner is a private class, no class other than Outer can refer to it. Therefore no class other than Outer can directly access the public data inside it either.
    Using inner classes with public data should be done only in situations in which the outer class is completely dependent on the inner class for its existence.

    If designed properly, inner classes preserve encapsulation while simplifying the implementation of related classes

    Preparing for chapter 5 test on Wednesday and getting ready for Midterm.

    Homework:
    Study for chapter 5 test.

    Chapter 4: Die ADT

    Chapter 4 – Writing Classes
    Back to topics from the previous lesson.

    1. Describe the instance data of the Die class.
    2. Which of the methods defined for the Die class can change the state of a Die object-that is, which of the methods assign values to the instance data?
    3. What happens when you pass an object to a print or println method?
    4. What is the scope of a variable?
    5. What are UML diagrams designed to do?

    Programming Projects::

    PP 4.3 Write an application (driver) that rolls a die and displays the result. Let the user pick the number of sides on the die. Use the Die class from this chapter to represent the die in your program.
    Include a UML class diagram.

    UML Basics

    PP 4.4 Design and implement a class called PairOfDice_YI, with two six-sided Die objects. Create a driver class called BoxCars_YI with the main method that rolls a PairOfDice_YI object 1000 times, counting the number of boxcars (two sixes) that occur. Print a full sentence with the outcome. Run the driver/test class at least 3 times.
    Include a UML class diagram.

    PP 4.5 Using the PairOfDice_YI class from Programming Project 4.4, design and implement a class to play a game called Pig_YI. In this game, the user competes against the computer. On each turn, the player rolls a pair of dice and adds up his or her points. Whoever reaches 100 points first, wins. If a player rolls a 1, he or she loses all points for that round and the dice go to the other player. If a player rolls two 1s in one turn, the player loses all points earned so far in the game and loses control of the dice. The player may voluntarily turn over the dice after each roll. So the player must decide to either roll again (be a pig) and risk losing points, or give up the dice, possibly letting the other player win. Set up the computer player so that it always gives up the dice after getting 20 or more points in a round.
    Draw a flowchart.

    Flowcharts: Most used shapes and Examples

    Use draw.io or google draw for the flowchart.
    Screen Shot 2014-09-28 at 3.36.01 PM

    Die.java

    //********************************************************************
    //  Die.java       Author: Lewis/Loftus/Cocking
    //
    //  Represents one die (singular of dice) with faces showing values
    //  between 1 and the number of faces on the die.
    //********************************************************************
    
    import java.util.Random;
    public class Die
    {
       private final int MIN_FACES = 4;
    
       private static Random generator = new Random();
       private int numFaces;   // number of sides on the die
       private int faceValue;  // current value showing on the die
    
       //-----------------------------------------------------------------
       //  Defaults to a six-sided die. Initial face value is 1.
       //-----------------------------------------------------------------
       public Die ()
       {
          numFaces = 6;
          faceValue = 1;
       }
    
       //-----------------------------------------------------------------
       //  Explicitly sets the size of the die. Defaults to a size of
       //  six if the parameter is invalid.  Initial face value is 1. 
       //-----------------------------------------------------------------
       public Die (int faces)
       {
          if (faces < MIN_FACES)
             numFaces = 6;
          else
             numFaces = faces;
    
          faceValue = 1;
       }
    
       //-----------------------------------------------------------------
       //  Rolls the die and returns the result.
       //-----------------------------------------------------------------
       public int roll ()
       {
          faceValue = generator.nextInt(numFaces) + 1;
          return faceValue;
       }
    
       //-----------------------------------------------------------------
       //  Returns the current die value.
       //-----------------------------------------------------------------
       public int getFaceValue ()
       {
          return faceValue;
       }
    }
    

    [collapse]

    Special Day: Pi Day Activity

    pi1

    Monday is Pi Day – We will have a pi-day activity ending on Monday.
    Starting today we are celebrating Pi day by preparing to write a program to do one of the following:
    1. Calculate the digits of Pi to highest possible precision. DOCUMENT YOUR MATHEMATICAL EXPRESSION AND THE LINK TO THE RESOURCE.
    2. Illustrate how Pi is used in a circle.
    3. Illustrate how Pi can be applied.
    4. Illustrate how Pi was discovered by telling an interactive story. “Choose your own adventure” type of story.

    The programs will be judge based on ingenuity and/or creativity.
    NOTE: You can use online resources to help you develop your program. There are good algorithms online. You can not use already written programs.
    Include any links used for your resources.

    If you like to memorize some of the digits of pi, there will be a competition on Friday. The student who can write the most digits without any help, get a small trophy.

    Homework: Explore and investigate the uses and history of pi.

    Pi Day The Gridworld

    March 12th, 2014

    Screen Shot 2014-03-12 at 9.40.23 AM

    Friday is Pi Day – We will have a pi-day activity
    Starting tomorrow we are celebrating Pi day by writing a program to do one of the following:
    1. Calculate the digits of Pi to highest possible precision
    2. Illustrate how Pi works
    3. Illustrate how Pi was discovered

    The programs will be judge based on ingenuity and/or creativity.
    NOTE: You can use online resources to help you develop your program. You can not use already written programs.

    Case Study: The Gridworld

    Screen Shot 2014-03-04 at 10.35.50 AM

    Classwork:
    Group Activity 1-2 to create the Jumper class and the runner program.

    Homework:
    write the code for the Jumper class and the runner program.

    Chapter 6 Review

    For review Array and Big-O Review for Chapter 6 Test, question 11 (39)

    If we trace the code with num = 20, how many times would the inner loop run?

    While Delta < 40
    Delta = 2, k = 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 → 10
    Delta = 4, k = 2, 6, 10, 14, 18 → 5
    Delta = 8, k = 4, 12, 20 → 3
    Delta = 16, k = 8 → 1
    Delta = 32, k = 16 → 1
    10 + 5 + 3 + 1 + 1 = 20
    
    

    Answer is C: O(n)
    Note: you will not get this type of question tomorrow.

    Solutions for the previous review:
    2. D
    3. C
    4. B
    5. C
    6. E
    7. C
    8. A
    9. C
    10. B
    11. D

    Topics:
    Arrays – Concepts and applications
    ArrayLists
    Searches: linear and binary – Concepts and tracing, Big-O, average, best and worse cases.
    Sorts: Insertion and Selection – Concepts and tracing, Big-O, average, best and worse cases.

    Study Guide:
    Self-Review problems, T/F questions, MC questions and SA exercises.
    Homework assignment from last Friday