Saturday, December 3, 2011

Class Definition » Declare Object

Using Objects
class Point {
  double x;

  double y;

  Point(double xVal, double yVal) {
    x = xVal;
    y = yVal;
  }

  Point(final Point oldPoint) {
    x = oldPoint.x;
    y = oldPoint.y;
  }

  void move(double xDelta, double yDelta) {
    x += xDelta;
    y += yDelta;
  }

  double distance(final Point aPoint) {
    return Math.sqrt((x - aPoint.x) * (x - aPoint.x) + (y - aPoint.y) * (y - aPoint.y));
  }

  public String toString() {
    return Double.toString(x) + ", " + y;
  }
}

// You can use Point objects in the definition of the class Line:

class Line {
  Point start;

  Point end;

  Line(final Point start, final Point end) {
    this.start = new Point(start);
    this.end = new Point(end);
  }

  Line(double xStart, double yStart, double xEnd, double yEnd) {
    start = new Point(xStart, yStart);
    end = new Point(xEnd, yEnd);
  }

  double length() {
    return start.distance(end);
  }

  public String toString() {
    return "(" + start + "):(" + end + ")";
  }
}


public class MainClass{
  public static void main(String[] arg){
    Line l1 = new Line(new Point(1,2), new Point(3,4));
    
    System.out.println(l1);
  }
  
}
 
Output
(1.0, 2.0):(3.0, 4.0)
 
Demonstrates that all classes 
descend from the type java.lang.Object 
/*
 *     file: ObjectIsGod.java
 *  package: oreilly.hcj.review
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */


/**  
 * Demonstrates that all classes descend from the type <tt>java.lang.Object</tt>.
 *
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision: 1.3 $
 */
public class ObjectIsGod {
  /** 
   * Main Method.
   *
   * @param args Command line arguments.
   */
  public static final void main(final String[] args) {
    System.out.println(SomeClass.class + " --|> " + SomeClass.class.getSuperclass());
    System.out.println(SomeOtherClass.class + " --|> "
                       + SomeOtherClass.class.getSuperclass());
  }

  /**  
   * Class with implicit java.lang.Object inheritance.
   */
  public class SomeClass {
  }

  /**  
   * Class with explicit java.lang.Object inheritance.
   */
  public class SomeOtherClass extends Object {
  }
}

/* ########## End of File ########## */
 
 
Demonstration of the Pointers and References Concept
/*
 *     file: PointersAndReferences.java
 *  package: oreilly.hcj.review
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */


import java.util.Vector;

/**  
 * Demonstration of the Pointers and References Concept.
 *
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision: 1.3 $
 */
public class PointersAndReferences {
  /** 
   * Main method.
   *
   * @param args Command Line arguments.
   */
  public static final void main(final String[] args) {
    Vector source = new Vector();
    source.add("O'Reilly");
    source.add("XML");
    source.add("Java");
    System.out.println("Original Vector");
    System.out.println(source.toString());
    // -- Try the first method. 
    someMethod(source);
    System.out.println("After first method.");
    System.out.println(source.toString());
    // -- Try the second method. 
    someOtherMethod(source);
    System.out.println("After second method.");
    System.out.println(source.toString());
  }

  /** 
   * Try using a vector without changing it.
   *
   * @param source The source Vector.
   */
  public static void someMethod(Vector source) {
    Vector target = source;
    target.add("Swing");
  }

  /** 
   * Try using a vector without changing it with final parameter.
   *
   * @param source The source Vector.
   */
  public static void someOtherMethod(final Vector source) {
    Vector target = source;
    target.add("JFC");  // ouch, still changes v.
    // source = new Vector(); // compiler error.
  }
}

/* ########## End of File ########## */
 
 
Implements a manager of lists that stores the lists by key
/*
 *     file: Inference.java
 *  package: oreilly.hcj.tiger
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
 ########## DO NOT EDIT ABOVE THIS LINE ########## */

import java.util.ArrayList;
import java.util.List;

/**
 * Implements a manager of lists that stores the lists by key.
 */
public class InferenceDemo {
  static int callCount = 0;

  /** Second. */
  public static <Type extends Number> Type someMethod(final Type num) {
    System.out.print("Second==> ");
    return num;
  }

  /** Third. */
  public static <Type> Type someMethod(final Type obj, List<Type> list) {
    System.out.print("Third==> ");
    return obj;
  }

  /** Fourth. */
  public static <Type> List<Type> someMethod() {
    System.out.print("Fourth==> ");
    return new ArrayList<Type>();
  }

  /** Fifth. */
  public static void someMethod(final Object obj) {
    System.out.print("Fifth==> ");
  }

  /** Sixth. */
  public static void someMethod(final String str) {
    System.out.print("Sixth==> ");
  }

  /** Seventh. */
  public static <Type> Type someOtherMethod(final Type obj, List<? extends Type> list) {
    System.out.print("Seventh==> ");
    return obj;
  }

  /** Demonstrate the rules. */
  public final static void main(final String[] args) {
    System.out.println();

    // Picks Sixth
    System.out.print("\n1) ");
    someMethod("Hello");

    // Ambiguous, wont compile.
    // System.out.print("\n2) ");
    // someMethod(new C());

    // Ambiguous, wont compile.
    // First and Fifth mask each other and can never be called.
    // System.out.print("\n3) ");
    // someMethod(new Object());

    // Picks Second
    System.out.print("\n5) ");
    someMethod(new Integer(5));

    // Picks Second
    System.out.print("\n6) ");
    someMethod(5);

    // Picks Fourth
    System.out.print("\n7) ");
    List<Integer> listOne = someMethod();
    listOne.add(new Integer(5));

    System.out.print("\n7a) ");
    List<String> listTwo = someMethod();
    listTwo.add(new String("Hello"));

    System.out.print("\n7b) ");
    Object listThree = someMethod();
    System.out.println(listThree.getClass());
    // listThree.add( ... ); // Cant put anything into this list

    // -- Make some lists --
    List<A> listOfA = new ArrayList<A>();
    listOfA.add(new A());

    List<B> listOfB = new ArrayList<B>();
    listOfB.add(new B());

    // Picks
    System.out.print("\n8) ");
    someMethod(5, new ArrayList<Integer>());

    // Wont compile: No such type. Since A can not necessarily be promoted to B.
    // System.out.print("9) ");
    // someMethod(new A(), listOfB);

    // Picks Three: Works because B can be demoted to A
    System.out.print("\n10) ");
    someMethod(new B(), listOfA);

    // Picks Seventh
    System.out.print("\n11) ");
    someOtherMethod(new A(), listOfB);

    // Picks Seventh
    // Works even though it probably shouldnt. The someOtherMethod() signature
    // implies
    // that the type of the component of the ist should be a subtype of the type
    // used
    // for obj. However, in this case first is a List<A> and A clearly isnt a
    // subtype
    // of B. Is this a bug?
    System.out.print("\n12) ");
    someOtherMethod(new B(), listOfA);

    // Really weird as the two types arent even remotely related. This should
    // probably
    // be rejected by the compiler but it doesnt seem to be enforcing its
    // bounds.
    System.out.print("\n13) ");
    List<String> listOfString = new ArrayList<String>();
    listOfString.add("Hello");
    someOtherMethod(new Integer(5), listOfString);

    // Doesnt work even though the spec says it should:
    // System.out.print(I"14)");
    // A value = <A>someMethod(new B(), new ArrayList<A>());

    // Picks Fourth: The type of the list returned by SomeMethod is
    // List<Integer>
    System.out.print("\n15) ");
    someMethod(5, someMethod());

    // Picks Fourth: The type of the list returned by SomeMethod is List<String>
    System.out.print("\n16) ");
    someMethod("Hello", someMethod());
  }

  private static class A {
  }

  private static class B extends A {
  }

  private static class C extends B {
  }
}

/* ########## End of File ########## */
 
 
http://www.java2s.com/Tutorial/Java/0100__Class-Definition/Catalog0100__Class-Definition.htm
»»  READMORE...

Friday, December 2, 2011

Putting test code in a nested class
public class MainClass {
  public MainClass() {
  }

  public void f() {
    System.out.println("f()");
  }

  public static class Tester {
    public static void main(String[] args) {
      MainClass t = new MainClass();
      t.f();
    }
  }
}
 
 
With concrete or abstract classes, inner classes are the only
way to produce the effect of multiple implementation inheritance.

class D {
}

abstract class E {
}

class Z extends D {
  E makeE() {
    return new E() {
    };
  }
}

public class MainClass {
  static void takesD(D d) {
  }

  static void takesE(E e) {
  }

  public static void main(String[] args) {
    Z z = new Z();
    takesD(z);
    takesE(z.makeE());
  }
}
 
 Local inner class can have a constructor    
 
interface Counter {
  int next();
}

public class MainClass{
  
  private int count = 0;
  Counter getCounter(final String name) {
    // A local inner class:
    class LocalCounter implements Counter {
      public LocalCounter() {
        // Local inner class can have a constructor
        System.out.println("LocalCounter()");
      }
      public int next() {
        System.out.print(name); // Access local final
        return count++;
      }
    }
    return new LocalCounter();
  }

  
  public static void main(String[] args) {
    MainClass lic = new MainClass();
    Counter c1 = lic.getCounter("Local inner ");
  }
}
 
http://www.java2s.com/Tutorial/Java/0100__
Class-Definition/Catalog0100__Class-Definition.htm
»»  READMORE...
Nested classes can access all members of all levels
of the classes they are nested within
class MyClass {
  private void f() {}
  class A {
    private void g() {}
    public class B {
      void h() {
        g();
        f();
      }
    }
  }
}

public class MainClass {
  public static void main(String[] args) {
    MyClass a = new MyClass();
    MyClass.A innerA = a.new A();
    MyClass.A.B innerb = innerA.new B();
    innerb.h();
  }
}

Proper inheritance of an inner class.
class A {
  protected class InnerA {
    public InnerA() {
      System.out.println("A.InnerA()");
    }

    public void f() {
      System.out.println("A.InnerA.f()");
    }
  }

  private InnerA y = new InnerA();

  public A() {
    System.out.println("New A()");
  }

  public void insertYolk(InnerA yy) {
    y = yy;
  }

  public void g() {
    y.f();
  }
}

class B extends A {
  public class InnerB extends A.InnerA {
    public InnerB() {
      System.out.println("B.InnerB()");
    }

    public void f() {
      System.out.println("B.InnerB.f()");
    }
  }

  public B() {
    insertYolk(new InnerB());
  }

}

public class MainClass {
  public static void main(String[] args) {
    A e2 = new B();
    e2.g();
  }
}
output
A.InnerA()
New A()
A.InnerA()
B.InnerB()
B.InnerB.f()
 
Using inner classes for callbacks 
interface InterfaceA {
  void increment();
}

class ClassA implements InterfaceA {
  private int i = 0;

  public void increment() {
    i++;
    System.out.println(i);
  }
}

class ClassB {
  void increment() {
    System.out.println("Other operation");
  }

  static void f(ClassB mi) {
    mi.increment();
  }
}

class ClassC extends ClassB {
  private int i = 0;

  private void incr() {
    i++;
    System.out.println(i);
  }

  private class Closure implements InterfaceA {
    public void increment() {
      incr();
    }
  }

  InterfaceA getCallbackReference() {
    return new Closure();
  }
}

class Caller {
  private InterfaceA callbackReference;

  Caller(InterfaceA cbh) {
    callbackReference = cbh;
  }

  void go() {
    callbackReference.increment();
  }
}

public class MainClass {
  public static void main(String[] args) {
    ClassA c1 = new ClassA();
    ClassC c2 = new ClassC();
    ClassB.f(c2);
    Caller caller1 = new Caller(c1);
    Caller caller2 = new Caller(c2.getCallbackReference());
    caller1.go();
    caller1.go();
    caller2.go();
    caller2.go();
  }
}
Returning a reference to an inner class
class MyClass {
  private class ClassB implements B {
    private int i = 11;

    public int value() {
      return i;
    }
  }

  protected class ClassA implements A {
    private String label;

    private ClassA(String whereTo) {
      label = whereTo;
    }

    public String readLabel() {
      return label;
    }
  }

  public A dest(String s) {
    return new ClassA(s);
  }

  public B cont() {
    return new ClassB();
  }
}

public class MainClass {
  public static void main(String[] args) {
    MyClass p = new MyClass();
    B c = p.cont();
    A d = p.dest("A");
  }
}

interface B {
  int value();
}

interface A {
  String readLabel();
}
»»  READMORE...
Nesting a class within a scope.
public class MainClass {
  private void method(boolean b) {
    if (b) {
      class A {
        private String id;

        A(String s) {
          id = s;
        }

        String getSlip() {
          return id;
        }
      }
      A ts = new A("slip");
      String s = ts.getSlip();
    }
    // Can't use it here! Out of scope:
    // ! A ts = new A("x");
  }

  public void track() {
    method(true);
  }

  public static void main(String[] args) {
    MainClass p = new MainClass();
    p.track();
  }
}
Nested classes (static inner classes)
public class MainClass {
  private static class ClassA implements A {
    private int i = 11;

    public int value() {
      return i;
    }
  }

  protected static class ClassB implements B {
    private String label;

    private ClassB(String whereTo) {
      label = whereTo;
    }

    public String readLabel() {
      return label;
    }

    // Nested classes can contain other static elements:
    public static void f() {
    }

    static int x = 10;

    static class InnerInnerClass {
      public static void f() {
      }

      static int x = 10;
    }
  }

  public static B dest(String s) {
    return new ClassB(s);
  }

  public static A cont() {
    return new ClassA();
  }

  public static void main(String[] args) {
    A c = cont();
    B d = dest("A");
  }
}

interface A {
  int value();
}

interface B {
  String readLabel();
}
An inner class cannot be overriden like a method
class A {
  private InnerA y;
  protected class InnerA {
    public InnerA() { System.out.println("A.InnerA()"); }
  }
  public A() {
    System.out.println("New A()");
    y = new InnerA();
  }
}

class B extends A {
  public class InnerB {
    public InnerB() { System.out.println("B.InnerB()"); }
  }
}

public class MainClass{
  public static void main(String[] args) {
    new B();
  }
}
Two ways that a class can implement multiple interfaces
interface A {
}

interface B {
}

class X implements A, B {
}

class Y implements A {
  B makeB() {
    // Anonymous inner class:
    return new B() {
    };
  }
}

public class MainClass {
  static void takesA(A a) {
  }

  static void takesB(B b) {
  }

  public static void main(String[] args) {
    X x = new X();
    Y y = new Y();
    takesA(x);
    takesA(y);
    takesB(x);
    takesB(y.makeB());
  }
}
»»  READMORE...

Class Definition » Nested Classes

Creating instances of inner classes

public class MainClass {
  class A {
    private int i = 11;

    public int value() {
      return i;
    }
  }

  class B {
    private String label;

    B(String whereTo) {
      label = whereTo;
    }

    String readLabel() {
      return label;
    }
  }

  public static void main(String[] args) {
    MainClass p = new MainClass();
    // Must use instance of outer class
    // to create an instances of the inner class:
    MainClass.A c = p.new A();
    MainClass.B d = p.new B("A");
  }
}
Nested Classes
class Outside {

  public class Inside {
  }
}

public class MainClass {
  public static void main(String[] arg) {
    Outside outer = new Outside();
    Outside.Inside inner = outer.new Inside();
  }
}
output
Nested Classes
 
Creating a new nested object outside 
class Outside {
  public class Inside {
  }

  public Outside() {
    Inside inner = new Inside();


    
  }
}
Static Nested Classes
public class Outside {
  public static class Skinside {

  }

  public class Inside {

  }

}

public class MainClass {

  public static void main(String[] arg) {
    Outside.Skinside example = new Outside.Skinside();
  }

}
 Creating inner classes
public class MainClass {
  class A {
    private int i = 11;

    public int value() {
      return i;
    }
  }

  class B {
    private String label;

    B(String whereTo) {
      label = whereTo;
    }

    String readLabel() {
      return label;
    }
  }

  // Using inner classes looks just like
  // using any other class, within MainClass:
  public void ship(String dest) {
    A c = new A();
    B d = new B(dest);
    System.out.println(d.readLabel());
  }

  public static void main(String[] args) {
    MainClass p = new MainClass();
    p.ship("AAA");
  }
}
Defining references to inner classes
public class MainClass {
  class A {
    private int i = 11;

    public int value() {
      return i;
    }
  }

  class B {
    private String label;

    B(String whereTo) {
      label = whereTo;
    }

    String readLabel() {
      return label;
    }
  }

  public B to(String s) {
    return new B(s);
  }

  public A cont() {
    return new A();
  }

  public void ship(String dest) {
    A c = cont();
    B d = to(dest);
    System.out.println(d.readLabel());
  }

  public static void main(String[] args) {
    MainClass p = new MainClass();
    p.ship("A");
    MainClass q = new MainClass();

    MainClass.A c = q.cont();
    MainClass.B d = q.to("A");
  }
}
Nesting a class within a method
public class MainClass {
  public A dest(String s) {
    class B implements A {
      private String label;

      private B(String whereTo) {
        label = whereTo;
      }

      public String readLabel() {
        return label;
      }
    }
    return new B(s);
  }

  public static void main(String[] args) {
    MainClass p = new MainClass();
    A d = p.dest("A");
  }
}

interface A {
  String readLabel();
}
»»  READMORE...