Tuesday, November 29, 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(5new 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 {
  }

  private static class extends {
  }

  private static class extends {
  }
}

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

Monday, November 28, 2011

Class Definition » static Member

Static Members
  1. Static members are not tied to class instances.
  2. Static members can be called without having an instance.
The out field in java.lang.System is static.
public class MainClass {

  public static void main() {
    System.out.println("123");

  }

}
the method main(the entry point to a class) is static because it must be
called before any object is created.





 Define the static member
  1. You can use the keyword static in front of a field or method declaration.
  2. The static keyword may come before or after the access modifier.
These two are correct:
public static int a;
static public int b;
To define a static method in the MathUtil class:
public class MathUtil {
    public static int add(int a, int b) {
        return a + b;
    }
}
  1. From inside a static method, you cannot call instance methods or instance fields because they only exist after you create an object.
  2. You can access other static methods or fields from a static method.
  3. You can only declare a static variable in a class level.
  4. You cannot declare local static variables even if the method is static.

Demonstrate static variables, methods, and blocks.


class UseStatic {
  static int a = 3;
  static int b;
   
  static void meth(int x) {
    System.out.println("x = " + x);
    System.out.println("a = " + a);
    System.out.println("b = " + b);
  }
   
  static {
    System.out.println("Static block initialized.");
    b = a * 4;
  }
   
  public static void main(String args[]) {
    meth(42);
  }
}
 
 
Inside main( ), the static method callme( )
and the static variable b are accessed outside of their class.
class StaticDemo {
  static int a = 42;
  static int b = 99;
  static void callme() {
    System.out.println("a = " + a);
  }
}
   
class StaticByName {
  public static void main(String args[]) {
    StaticDemo.callme();
    System.out.println("b = " + StaticDemo.b);
  }
}
 
 
reference static field after declaration
public class ClassInitializer3 {
  static int classField1 = 1;
  static int classField2 = + classField1;

  public static void main(String[] args) {
    System.out.println(classField1);
    System.out.println(classField2);
  }
}
 
 
static section of Initializer
 
public class ClassInitializer5 {
  static String tz;

  static {
    java.util.Properties p = System.getProperties();
    p.list(System.out);
    tz = p.getProperty("user.timezone");
    if (tz.equals(""))
      tz = "Default";
  }

  public static void main(String[] args) {
    System.out.println("timezone = " + tz);
  }
}
 
 
static section Initializer and logic
public class ClassInitializer6 {
  static int classField = 3;

  static {
    System.out.println(" : " + classField);

    classField = 1;
    for (int i = 2; i < 6; i++)
      classField *= i;
  }

  static {
    System.out.println(" = " + classField);
  }

  public static void main(String[] args) {
    System.out.println(classField);
  }
}
 
 
Initializer for final static field
public class ClassInitializer7
{
   final static int classField;

   static
   {
      classField = 29;
   }

   public static void main (String [] args)
   {
      System.out.println (classField);
   }
}

Demonstrates Static nested Classes
/*
 *     file: StaticNestedClassDemo.java
 *  package: oreilly.hcj.nested
 *
 * 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 Static nested Classes.
 
 @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 @version $Revision: 1.3 $
 */
public class StaticNestedClassDemo {
  /**
   * Main method.
   
   @param args
   *          Command line arguments.
   */
  public static void main(final String[] args) {
    OuterClass.SomeClass obj = new OuterClass.SomeClass();
    obj.someMethod();
    // OuterClass.SomeOtherClass prot = new OuterClass.SomeOtherClass(); // <=
    // Compiler error
    OuterClass.doPrivate();
  }
}

/* ########## End of File ########## */
/*
 * file: OuterClass.java package: oreilly.hcj.nested
 
 * 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 ##########
 */

/**
 * Demonstration of some static nested classes.
 
 @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 @version $Revision: 1.5 $
 */
class OuterClass {
  /** Holds the name. */
  private static final String name = "Robert";

  /** Holds the company. */
  private static String company = "O'Reilly";

  /** Holds a value. */
  private int value = 5;

  /**
   * Getter for the property company.
   
   @return The current company.
   */
  public static String getCompany() {
    return company;
  }

  /**
   * Getter for the variable name.
   
   @return The current name.
   */
  public static String getName() {
    return name;
  }

  /**
   * Getter for the variable company.
   
   @return the current company.
   */
  public int getValue() {
    return value;
  }

  /**
   * Demo of instatiation of a private class.
   */
  public static void doPrivate() {
    SomeOtherClass cl = new SomeOtherClass();
    cl.someMethod();
  }

  /**
   * A demo nested static class.
   
   @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
   @version $Revision: 1.5 $
   */
  public static class SomeClass {
    /**
     * a demo method.
     */
    public void someMethod() {
      System.out.println(company);
      System.out.println(name);
      // System.out.println(value); // <= Compiler error
    }
  }

  /**
   * A demo nested static class.
   
   @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
   @version $Revision: 1.5 $
   */
  protected static class YetAnotherClass {
  }

  /**
   * A demo nested static class.
   
   @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
   @version $Revision: 1.5 $
   */
  private static class SomeOtherClass {
    /**
     * a demo method.
     */
    public void someMethod() {
      System.out.println("Protect me!");
    }
  }
}

/* ########## End of File ########## */
 
 
Reference inner static class
class MyClassesDemo {
  public static void main(String[] args) {
    MyClass tlc = new MyClass();

    MyClass.NestedMyClass ntlc;
    ntlc = new MyClass.NestedMyClass();
  }
}

class MyClass {
  private int i;
  private static String name = "MyClass";
  {
    System.out.println("Assigning 1 to i");
    i = 1;
  }

  static class NestedMyClass {
    int j;
    {
      System.out.println("Assigning 2 to j");
      j = 2;
      System.out.println(name);
    }
  }
}
 
Static field, constructor and exception
public class Main {
  static Bar bar;

  static {
    try {
      bar = new Bar();
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] argv) {
    System.out.println(bar);
  }
}

class Bar {
  public Bar() throws Exception {
  }

  public String toString() {
    return "Bar";
  }
}
 
http://www.java2s.com/Tutorial/Java/0100__
Class-Definition/Catalog0100__Class-Definition.htm
»»  READMORE...