
%\documentclass[11pt]{article}
\documentclass{acmtrans2m}

%\setlength{\oddsidemargin}{0in}
%\setlength{\evensidemargin}{0in}
%\setlength{\textwidth}{6.5in}
%\setlength{\textheight}{9.5in}


\acmVolume{csci210: Data Structures }
\acmYear{Spring 2009}
\markboth{Java Basics }{Java Basics}


\title{Java Basics}
\date{}
\author{}


\begin{document}
\maketitle




\section{Inheritance} 

Code sharing is a good thing. First, you do not want to re-write the
same stuff more than once. Also, code is likely to be more reliable as
it only has to be debugged once.  A mechanism for sharing code is
\emph{inheritance}.

\begin{verbatim}
class A {
   //variables
   //methods
}
class B extends A {
  //class B inherits ALL variables and methods of class A
}
\end{verbatim}

We say that class A is the parent of class B, or the
\emph{super-class} of class B; class B is the \emph{sub-class}.
A class can inherit from a single other class (in Java). 


The sub-class inherits all the variables and methods in the
super-class. It is as though the variables and methods of the
super-class would be textually present in the sub-class.


Example: 
\begin{verbatim}
class OneDPoint

class TwoDPoint extends OneDPoint 

class ThreeDPoint extends TwoDPoint 

\end{verbatim}


Example: 
\begin{verbatim}
class Person {
   String name;  //the name
   
   void Person(String s) {
       name = new String(s); 
   }

   String getName() {
      return name; 
   }
}; 
class Student extends Person {

  int class; //the class of graduation

  void Student(String n, int year) {
    super(n); 
    class = year; 
  }
}
\end{verbatim}

Now we can say: 
\begin{verbatim}
class Student s = new Student("Jon Myers); 
System.out.println("name is " + s.getName()); 
\end{verbatim}


In the constructor of the sub-class, the first thing to do is invoke
the constructor of the super-class.

In our toy example above this makes no sense because class Person is
empty and it does not even have a constructor.  But in general it takes
some work to ``construct'' a parent class, so in a sub-class we first
need to invoke the appropriate constructor and pass it the arguments
that we want.


Object-oriented programming allows to define class hierarchies. That
is, it allows for classes to inherit from other classes, which inherit
from other classes, and so on. 


\subsection{Overriding methods} 

We said earlier that a sub-cass inherits all the methods of the parent
classes. Sometimes it is the case that a sub-class is not happy with
the definition of a method inherited from the parent; it might want to
do something different.  In this case it may chose to redefine the
method. This is called ``overriding a method''.


\subsection{The Java class hierarchy}

In Java the root of all classes is class \texttt{Object}. That is,
every Java class inherits from it.

Class \texttt{Object} has no variables, but has a bunch of methods.
Thus any class will inherit these methods, and their default
definition in class \texttt{Object}. Here are a few that we'll be using later: 

\begin{verbatim}
//Indicates whether some other object is "equal to" this one.
boolean equals(Object obj);

//Returns a string representation of the object.
String toString() 

\end{verbatim}

\newpage
\section{Java Interfaces}

Java has the concept of an \texttt{interface}. An interfaces is like a
class, just that it does not give the implementation, just the
\emph{signatures} of the methods. All methods in an interface must be
public.

\begin{verbatim}
public interface xxx {

// list the signatures of the methods
}
\end{verbatim}

For example, here is an interface that you'll use all the time: 
\begin{verbatim}
public interface MouseListener {
   public void  mouseClicked(MouseEvent e); 
   public void	mouseEntered(MouseEvent e);
   public void	mouseExited(MouseEvent e);  
   public void	mousePressed(MouseEvent e);
   public void	mouseReleased(MouseEvent e); 
}
\end{verbatim}

Interfaces are used to describe a class \emph{without} an
implementation.

A class may chose to \emph{implement} an interface, or several. Every class that
implements an interface must define all methods in the interface.

When compiling a class that implements an interface, the compiler
checks to see that \emph{all} methods specified in the interface are
implemented; the parameter types and return type must match; if not,
it gives an error. So you can think of an interface is a way of
specifying a set of methods that an object must support. An interface
is a contract between a class and the outside world.

It is possible that a class implements several interfaces---then it
needs to implement \emph{all} methods in \emph{all} interfaces.

You probably won't be defining interfaces, but you'll write all the
time classes that implement interfaces.


Interfaces are useful because sometimes you don't know exactly what
class you'll be using, you just know it has to have some
functionality. You can think of interfaces as \emph{generic} classes.
For example, here is the set of methods that we'd expect from a
\texttt{List}:

\begin{verbatim}
public interface List {

  //return the size of the list 
  public int size(); 

  //return true if list is empty
  public boolean isEmpty(); 

  //return true if the list contains the given element 
  public boolean contains(Object value); 

  //add one element to the list 
  public void add(Object value); 

  //remove the element from the list 
  public void remove(Object value); 
}
\end{verbatim} 

Suppose we have two classes that implement \texttt{List}

\begin{verbatim}
 public class ArrayList implements List {
 
   //... implements all methods in the interface, and possibly more 
 }

 public class Vector implements List {
 
   //... implements all methods in the interface, and possibly more 
 }
 \end{verbatim}


Now we can write a piece of code that works with a generic List: 
\begin{verbatim}
void collectData(List l) {
    ....
} 
\end{verbatim}
and we can call this passing an argument either an \texttt{ArrayList}
or a \texttt{Vector}.

 


\section{Inheritance and Dynamic type-casting}

Java performs automatic type conversion from a sub-type to a
super-type. That is, if a method requires a parameter of type A, we
can call the method with a parameter that is a sub-class of
A. Basically this says that any class that inherits from A can be used
in place of type A.

One way you will see this is when writing, say, a class that is
supposed to handle an array of objects--- but we don't know what the
type of the objects will be. So we declare the data as: 
\begin{verbatim}
class Vector {
   Object[]  myArray; 
   ...

   //insert x in the array
   void insert(Object x) {...}
}
\end{verbatim}


Then we can use Vector to hold \emph{any} objects. 

\begin{verbatim}
Vector v = new Vector(); 
v.insert(``snow''); 
v.insert(``cold''); 
\end{verbatim}




\section{Methods inherited from Java class Object}



\subsection{\texttt{toString()}}

This is a method that returns the string representation of the object
its called on. It is defined in class \texttt{Object} and therefore
inherited by all objects.

For example, 
\begin{verbatim}
class Point {
     private int x, y;
    
     public Point(int x, int y) {
        this.x = x;
        this.y = y;
     }
     public int getX() {
        return x;
     }
     public int getY() {
        return y;
     }
}
public class ToStringDemo {
     public static void main(String args[]) {
     Point p = new Point(10, 10);
    
     // using the Default Object.toString() Method
     System.out.println("Object toString() method : "+p);
    
     // implicitly call toString()
     String s = p + " testing";
     System.out.println(s);
     }
}
\end{verbatim}

Try playing with this. 

If you want more useful information about an object (for e.g. helpful
in debugging) you'll have to override the \texttt{toString} method:
\begin{verbatim}
public void toString() {
  System.out.println("x=" + x + ", y=" + y);
}
\end{verbatim}





\subsection{ \texttt{equals} vs. ==}
 
You have seen == on integers, and other primitive types. You can also
use == on objects. There is a difference though: on objects ==
determines whether two objects \emph{refer to the same object}. That
is, == compares \emph{reference}, not values.

\begin{verbatim}
SomeClass x, y, z; 

x = new SomeClass(); 
y = x; 
//then x==y  will return true 

z = a copy of x
//then x==z will return false, even though the values are equal
\end{verbatim}


What if we want to check whether the two objects have the same fields?
Any class has a (default) \texttt{equals()} method that is inherited
from class \texttt{Object}.  The default version of \texttt{equals()}
checks for equality of reference, just like ==.

Usually you are not interested whether the two objects refer to the
same object, but rather, whether two objects are equal---i.e. their
fields are equal.  If you want to check data equality, you need to
implement (override) .

This has been done for example on class String. The \texttt{equals}
method on class \texttt{String} checks for data equality.  For
example,
\begin{verbatim}
String s = "Bowdoin";
if (s.equals("bowdoin"))
\end{verbatim}
will return \texttt{true}.  








\section{\texttt{static} variables and methods}


When a number of objects are created from the same class, they each
have their own distinct copies of instance variables, stored in
different memory locations. 

A class can have variables that are declared \texttt{static}.  These
variables are associated with the \emph{class}, not with the instances
of the class (i.e. the objects).

The static variables are common to the class and are shared by all
instances of the class.  Any object can change the value of a class
variable; class variables can also be manipulated without creating an
instance of the class.

A static variable is accessed as \texttt{<class-name>.<variable-name>}.

Example: a BankAccount class can keep a static variable for the number
of accounts open. Every call to a constructor would increment this
variable. 

A common use of static variables is to define "constants". Examples
from the Java library are \texttt{Math.PI} or \texttt{Color.RED}. 


A method can also be declared \texttt{static}.  Then it is associated
with the class, and not with an object.  From inside a class it is
called by its name, just like a non-static method. From outside the
class it is called on the class
\texttt{<class-name>.<method-name>(<arguments>)}.

You may ask: when to declare a method static? When it performs a
function specific to the class, not to a specific object.
\begin{verbatim}
public class Math {
    ...
   //returns true if n is prime
   public static boolean isPrime(int n) {
       ...
   }
}
\end{verbatim}

To find whether a number is prime, you dont need to create a specific
object.  From outside the class, call \texttt{Math.isPrime(645)}.

A common use for static methods is to access static variables. 

The functions is \texttt{Math} are all static: \texttt{ Math.sin(x),
  Math.cos(x), Math.exp(d), math.pow(d1, d2)}.

Note: static methods cannot acces instance variables (there is no
instance), and cannot access \texttt{this} (there is no instance for
this to refer to).









\section{Scope} 

Types of variables in Java: 
\begin{enumerate}
\item  instance variables (non-static)
\item class variables (static variables)
\item local variables
\item parameters
\end{enumerate}

Scope: Within a method.  Between methods.  Between classes.

Variables must be declared within a class (instance variables or
global variables) or a method (local variables).

An instance variable is visible/accessible to all methods of that
class. If it is public, it is also visible outside the class.

A local variable is visible only inside the method; in the code
following its declaration, within the tightest enclosing {}.

The parameters of a method are visible (only) inside the method and do
not need to be re-declared inside.


\subsection{ \texttt{this}}
Used to refer to an instance variable that clashes with a parameter: 
\begin{verbatim}
class A { 
   private int age; 
 
public void setAge(int age) {
   this.age = age; 
}
\end{verbatim}


\subsection{Example}
\begin{verbatim}
public class ScopeTester {

    //instance variable
    private int x = 1;

    public void test1 (int x) {
	//a parameter shadows an instance variable
	System.out.println("x = " + x);
	x = 10; 
	System.out.println("x = " + x);
	System.out.println("this.x = " + this.x);
    }

    public void test2() {
	//you can redeclare an instance variable
	double x = 10.3;
	System.out.println("x=" + x);
	System.out.println("this.x=" + this.x);
    }

    public void print() {
	System.out.println("x=" + x);
    }

    public boolean equals (ScopeTester s) {
	return (x == s.x); 
    }

    public static void main (String args[]) {
	ScopeTester s = new ScopeTester(); 

	int a = 100; 
	System.out.println("before test1: a = " + a);
	s.test1(a);
	//a is changed in test1(), but not visible outside
	System.out.println("after test1: a = " + a);

	s.test2();
	s.print();

	ScopeTester x, y; 
	x = new ScopeTester(); 
	y = new ScopeTester();
	if (x==y) System.out.println("same object");
	else System.out.println("NOT same object");
	if (x.equals(y)) System.out.println("equal");
	else System.out.println("not equal");

	System.out.println("this is the default toString(): " + x);


    }
}
\end{verbatim}






\section{Programming with assertions}

A good programming practice in any language is to use assertions in 
the code to enforce invariants. 

For example, if at some point in a method we know that a variable say
x must be non-zero, we write:
\begin{verbatim}
 assert (x != 0); 
\end{verbatim}

When the code is executed, if x is non-zero, the assertion
succeeds. Otherwise, if x is zero, the assertions fails, and the
program terminates with an error.


In order to enable assertion you have to compile with the flag
\texttt{-ea}: 
\begin{verbatim}
javac -ea xxx.java
\end{verbatim}

Assertions don't have any effect on the code as such, they are just
used to make sure that certain conditions are true.  It is good
pratice and style to include assertions in your code. They help you
catch errors earlier.



\section{Testing and debugging}

If your program compiles, that does not mean it is correct. It can
still have bugs... that is, logical errors. You will find that you
will spend most of your time debugging your code. There is no recipe
on how to debug --- just plenty of print statements, and/or use BlueJ.

To find all possible bugs, you need to \emph{test} your program on
different inputs, and take into account all situations that may
appear.


\end{document}
%%% Local Variables: 
%%% mode: latex
%%% TeX-master: t
%%% End: 



%%% Local Variables: 
%%% mode: latex
%%% TeX-master: t
%%% End: 
