Title: Defining Classes Part 4
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Defining Classes Part 4

Information Hiding and Encapsulation

1. Information hiding or Abstraction - means that only necessary information is made public. Class internals is kept hidden.
2. Encapsulation - means grouping software into a unit in such a way that it is easy to use because there is a wel-defined simple interface. We create classes that group together data and methods that are related. Class internals is hidden inside the class and the public interfaces are made available in an
API - Application Programming Interface - in an API, you might specify the preconditions and postconditions for each method call
3. Another term that get thrown around is ADT - Abstract Data type. An ADT is a data type or class that is written using good information-hiding techniques. The Date class or perhaps the Rectangle class could claim to be an ADT.
4. See DateSixthTry.java. Note the usage of public and private to distinguish the parts that are public to the outside world and the parts that are considered internals to be hidden. Note the usage of public
Accessor methods - getXXXX - getDay, getMonth, getYear, etc.
Mutator methods - setXXXX - setDate, setMonth, setDay, setYear
5. Note that private data is available to any code inside the class but forbidden to any code outside of the class.

Overloading

- More than one method with the same name. Note that the calling sequence needs to be different. The method name plus the calling sequence creates the effective name or signature used by the compiler.
- Check out DateSixthTry.java and see the overloaded methods:

setDate(int, int, int)
setDate(String, int, int)
setDate(int)

dateOK(int, int, int)
dateOK(String, int, int)
- Rules for overriding:

  1. Number of arguments must match the number of formal parameters
  2. Java's first choice will be a perfect match of data types between arguments and formal parameters
  3. After that, Java will find the "closest" match for a call where the arguments can automatically converted.
  4. If Java can't figure out which call is the closest, you will get an ambiguous compile error


	void printSomething(int x, long y, double d) // Version 1
	     {
         System.out.println("int, long, double");
      }

	void printSomething(int x, int y, int  z) // Version 2
	     {
          System.out.println("int, int, int");
      }

	void printSomething(long x, long y, long z) // Version 3
	     {
          System.out.println("long, long, long");
      }
	
	int k1=0, k2=0, k3=0;
	long l1=0, l2=0, l3=0;
	double d=1.0;
	
	printSomething(k1, l1, d);  // Perfect fit with Version 1
	printSomething(k1, k2, k3); // Perfect fit with Version 2
	printSomething(l1, l2, l3); // Perfect fit with Version 3
	
	printSomething(k1, k2, d);  // Only Version 1 will work (convert second parameter)

// In the following there are no perfect fits.  Version 1 and 3 work.
// Both versions need one parameter conversion.  Compiler is likely to
// give a compile error because it isn't sure which one to pick.
	printSomething(k1, l2, l3);
    	
 // At this point you need to give the compiler a hint
 // so it can make a choice.  For example either of the
 // following will compile
  printSomething((long)k1, l2, l3);

  printSomething(k1, l2, (double)l3);
	// try others.
	
	

Try out the above in a Test program
- Note that the return type is not included in the signature of an overloaded method. The following is ambiguous:


	public int computeSomething(int n)
	{
	  //...
   return 0;
	}
	public double computeSomething(int n)  // Generates a compile error
	{
	   //...
    return 0.0;
	}
	
	
	 // perhaps you expected this to work with the above.
	 double answer = anObject.computeSomething(10);

  // What should the compiler do with:
  anObject.computeSomething(10);
	

Self Test Exercises from your textbook.

1. If a class is named CoolClass, what names are allowed as names for constructors in the class CoolClass
Don't think too long on this one.
2. Interesting "Self-Test" question from your textbook:


  public class YourClass
  {
     private int information;
     private char moreInformation;

     public YourClass(int newInfo, char moreNewInfo)
     {
       ...
     }
     public YourClass()
     {
       ...
     }
     public void doStuff()
     {
       ...
     }
 }



Which of the following are legal in a program that uses this class?


  YourClass anObject = new YourClass(42, 'A');         //OK
  YourClass anotherObject = new YourClass(41.99, 'A'); // Compile error
  YourClass yetAnotherObject = new YourClass();        //OK
  yetAnotherObject.doStuff();                          //OK
  YourClass oneMoreObject;                             //OK, but watch out:
                                                       // oneMoreObject = null
  oneMoreObject.doStuff();                             // Runtime exception
  oneMoreObject.YourClass(99, 'B');                    // Constructors don't get called like this


Initialization of Variables

1. Note that local variables must be initialized before they are used because the compiler will catch this error. Instance variables should be initialized, but the compiler doesn't (or can't) catch unitilialized instance variable errors. So consider the following code:


  public class Test {
    int xInstance;

    void doit()
    {
        int xLocal;

        System.out.println(xInstance);
        System.out.println(xLocal); // compile error
    }
    public static void main(String[] args) {
        Test t = new Test();
        t.doit();
    }
}


2. Instance variables in a class that aren't initialized will have a known value (i.e. they will not contain random garbage as you might expect in a language like C++). The standard defaults:
  - byte, char, short, int, long default to 0
  - float, double default to 0.0
  - Classes (i.e. String, Rectangle, Date, etc.) all default to null
3. Initializing instance variables can be done in the variable declaration, or they can be initialized by the Constructor. One way or another it is recommend that all instance variables are initialized by the time the constructor completes.

StringTokenizer

StringTokenizer(String str);
StringTokenizer(String str, String delimiters);
boolean hasMoreTokens();
String nextToken();
String nextToken(String delimiters);
int countTokens();

Testing StringTokenizer


import java.util.Scanner;
import java.util.StringTokenizer;


public class TestStringTokenizer {

    void test1(String s)
    {
        System.out.println("**************************************");
        StringTokenizer st = new StringTokenizer(s);
        System.out.println("Using new StringTokenizer(s)");

        System.out.println("test1: # tokens=" + st.countTokens());

        while (st.hasMoreTokens())
        {
            String next = st.nextToken();
            System.out.println(next);
        }
        System.out.println("----------------------------------");
    }
    void test2(String s)
    {
        System.out.println("**************************************");
        StringTokenizer st = new StringTokenizer(s, " ;,.\t");
        System.out.println("Using new StringTokenizer(s, \" ;,.\t\")");

        System.out.println("test2: # tokens=" + st.countTokens());

        while (st.hasMoreTokens())
        {
            String next = st.nextToken();
            System.out.println(next);
        }
        System.out.println("----------------------------------");
    }

    public static void main(String[] args) {
        System.out.println("Enter String for StringTokenizer");
        Scanner keyboard = new Scanner(System.in);
        String s = keyboard.nextLine();

        TestStringTokenizer t = new TestStringTokenizer();
        t.test1(s);
        t.test2(s);


    }

}



Exercises (these aren't assigned, but there for you if you have extra time):-)

1. Do Question 1 at the end of the chapter of 99 bottles of beer on the wall.
2. Implement the following (i.e. fill in code inside of {} ):


  class Number
  {
   Number(int x){}
   Number(String s){}	 // exits as soon as a non-digit occurs
   void add(Number n){}
   void add(int n){}
   void add(String s){} // exits as soon as a non-digit occurs
   boolean equals(Number n){}
   public String toString(){}
   int getNum(){}
 }


Create some code to use the Number class. Does Number have a default constructor?
3. Use the StringTokenizer class and the previous class to add up numbers of various bases. For example your program should be able to add up the following:

1234      1101     12ab     45      xyz
4. Create a Rectangle class with instance variables x, y, width, height and methods:
Rectangle union(Rectangle r); // Easier
Rectangle intersect(Rectangle r); // Quite tricky

Java Practice(JPHN):

1. (4 points) Go back to the Author's DateSixthTry. Create another class called TestDateSixthTry that constructs instances of DateSixthTry and calls the overloaded methods:
  1. setDate(int, int, int)
  2. setDate(String, int, int)
  3. setDate(int)
  4. What happens if we attempt to call the dateOK(String, int, int) method from TestDateSixthTry?
  5. How does DateSixthTry protect itself from a call to setDate("May", 33, 2984)?
2. (3 points) Determine which overloaded method gets called in each case of the following example.


public class Overloaded {
    void compute(int x)
    {
        System.out.println("compute(int x) called");
    }
    void compute(double x)
    {
        System.out.println("compute(double x) called");
    }

    void compute(int x, double y)
    {
        System.out.println("compute(int x, double y) called");
    }

    void compute(double x, double y)
    {
        System.out.println("compute(double x, double y) called");
    }

    public static void main(String[] args)
    {
        Overloaded ol = new Overloaded();
        int ix =1;
        double dx =1.0;
        long lx =1;

        ol.compute(ix);
        ol.compute(dx);
        ol.compute(lx);
        ol.compute(ix,dx);
        ol.compute(lx,lx);
    }

}


3. (3 points) Write a program that uses the StringTokenizer to print out all of the words in the following String:
"Hopefully the more I practice Java examples the more it begins to make sense"

Last Modified: December 22, 2014 11:24 PM