Sunteți pe pagina 1din 20

5.

 1. 4. Creating Objects of a Class public class MainClass{       Account account1 = new Account( 50.00 


class Sphere {    public static void main( String args[] ) {  class GradeBook ); // create Account object
  double radius; // Radius of a sphere       GradeBook myGradeBook = new GradeB {       Account account2 = new Account( -7.53 )
  Sphere() { ook();     private String courseName; // course nam ; // create Account object
  }       String courseName = "Java "; e for this GradeBook
  // Class constructor       myGradeBook.displayMessage( courseNa       System.out.printf( "account1 balance: $
  Sphere(double theRadius) { me );    // method to set the course name %.2f\n", account1.getBalance() );
    radius = theRadius; // Set the radius    }    public void setCourseName( String name  {       System.out.printf( "account2 balance: $
  } }       courseName = name; // store the course  %.2f\n\n", account2.getBalance() );
} name       
class GradeBook{    }       double depositAmount; // deposit amou
public class MainClass {    public void displayMessage( String course nt read from user
  public static void main(String[] arg){ Name ) {    // method to retrieve the course name
    Sphere sp = new Sphere();       System.out.printf( "Welcome to the grad    public String getCourseName()       depositAmount = 10.10;
  } e book for\n%s!\n",     {       account1.credit( depositAmount ); // add 
}          courseName );       return courseName; to account1 balance
   }    }
}       System.out.printf( "account1 balance: $
5. 1. 5. Checking whether the object %.2f\n", account1.getBalance() );
   // display a welcome message to the Grad       System.out.printf( "account2 balance: $
referenced was of type String
5. 1. 8. Class that contains a String eBook user %.2f\n\n", account2.getBalance() );
class Animal {
instance variable and methods to    public void displayMessage()
  public Animal(String aType) {
   {       depositAmount = 12.12; 
    type = aType; set and get its value
      System.out.printf( "Welcome to the grad       account2.credit( depositAmount ); // add 
  } public class MainClass
e book for\n%s!\n",  to account2 balance
  public String toString() { {
         getCourseName() );
    return "This is a " + type;    public static void main( String args[] )
   }       System.out.printf( "account1 balance: $
  }    { 
} %.2f\n", account1.getBalance() );
  private String type;       GradeBook myGradeBook = new GradeB
OUTPUT:       System.out.printf( "account2 balance: $
} ook(); 
Initial course name is: null %.2f\n", account2.getBalance() );
public class MainClass {
Welcome to the grade book for    }
  public static void main(String[] a) {       System.out.printf( "Initial course name is
Java!
    Animal pet = new Animal("a"); : %s\n\n",myGradeBook.getCourseName() );
}
    if (pet.getClass() == Animal.class) {
      System.out.println("it is an animal!");       String theName = "Java";
5. 1. 9. Class with a constructor to class Account
    } }}       myGradeBook.setCourseName( theName 
initialize instance variables {   
); // set the course name
   private double balance; // instance variabl
public class MainClass
e that stores the balance
5. 1. 7. Class declaration with a       myGradeBook.displayMessage(); {
   }    public static void main( String args[] ) 
method that has a parameter    // constructor  
}     {
   public Account( double initialBalance )     t2.f2(1); 5. A constructor never returns a value
   { class B {     t3.f3(1); 6. A constructor always has the same
      if ( initialBalance > 0.0 )    static A a = new A(1);   } name as the class.
         balance = initialBalance;    static B t2 = new B(); 7. A constructor may have zero argument,
   }   B() {   static C t3 = new C(); in which case it is called a no-argument
    System.out.println("Table()"); } (or no-arg, for short) constructor.
   public void credit( double amount )     staticA.f(1); 8. Constructor arguments can be used to
   {         } OUTPUT: initialize the fields in the object.
      balance = balance + amount; Bowl(1)
   }   void f2(int marker) { Bowl(2) The syntax for a constructor is as follows.
    System.out.println("f2(" + marker + ")"); Table()
   public double getBalance()   } f(1) constructorName (listOfArguments) {
   {   static A staticA = new A(2); Bowl(4)     [constructor body]
      return balance; } Bowl(5) }
   } Bowl(3) ----
class C { Cupboard()
}   A a = new A(3); f(2) public class MainClass {
Creating new Cupboard() in main   double radius;
OUTPUT: account1 balance: $50.00   static A staticA = new A(4); Bowl(3)   // Class constructor
account2 balance: $0.00 Cupboard()   MainClass(double theRadius) {
  C() { f(2)     radius = theRadius;
account1 balance: $60.10     System.out.println("Cupboard()"); Creating new Cupboard() in main   }
account2 balance: $0.00     staticA.f(2); Bowl(3)
  } Cupboard()
account1 balance: $60.10 f(2) 5. 2. 2. The Default Constructor
account2 balance: $12.12   void f3(int marker) { f2(1) public class MainClass {
    System.out.println("f3(" + marker + ")"); f3(1)   double radius;
  }
5. 1. 10. Specifying initial values in a   MainClass() {
class definition   static A staticA2 = new A(5); 5. 2. 1. Using Constructors
} 1. Every class must have at least one   }
class A {
  A(int marker) { constructor.
public class MainClass { 2. If there is no constructors for your class,   // Class constructor
    System.out.println("Bowl(" + marker + ")")
  public static void main(String[] args) { the compiler will supply a default   MainClass(double theRadius) {
;
    System.out.println("Creating new Cupboa constructor(no-arg constructor).     radius = theRadius;
  }
rd() in main"); 3. A constructor is used to construct an
    new C(); object.   }
  void f(int marker) {
    System.out.println("Creating new Cupboa 4. A constructor looks like a method and is
    System.out.println("f(" + marker + ")");
rd() in main"); sometimes called a constructor
  }
    new C(); method. 5. 2. 3. Multiple Constructors
}
class Sphere {   double xCenter;   static long l = 2L;   }
  int radius = 0;   double yCenter;   static short sh = 200; }
  Sphere() {   double zCenter;   static String str = "test";
    radius = 1; class Lunch extends Meal {
  }   Sphere() {   public static void main(String[] args) {   Lunch() {
  Sphere(int radius) {     radius = 1;     System.out.println("bool = " + bool);     System.out.println("Lunch()");
    this.radius = radius;   }     System.out.println("by = " + by);   }
  }     System.out.println("ch = " + ch); }
}   Sphere(double x, double y, double z) {     System.out.println("d = " + d);
    this();     System.out.println("f = " + f); class PortableLunch extends Lunch {
    xCenter = x;     System.out.println("i = " + i);   PortableLunch() {
5. 2. 4. Calling a Constructor From a     yCenter = y;     System.out.println("l = " + l);     System.out.println("PortableLunch()")
Constructor     zCenter = z;     System.out.println("sh = " + sh); ;
class Sphere {   }     System.out.println("str = " + str);   }
  int radius = 0;   } }
  double xCenter;   Sphere(int theRadius, double x, doubl }
  double yCenter; e y, double z) { class Sandwich extends PortableLunch {
  double zCenter;     this(x, y, z);   private Bread b = new Bread();
    radius = theRadius; 5. 2. 7. Order of constructor calls
  Sphere() {   } class Meal {   private Cheese c = new Cheese();
    radius = 1;      Meal() {
  }   // Create a sphere from an existing obj     System.out.println("Meal()");   private Lettuce l = new Lettuce();
  Sphere(double x, double y, double z) { ect   }
    this();   Sphere(final Sphere oldSphere) { }   public Sandwich() {
    xCenter = x;     radius = oldSphere.radius;     System.out.println("Sandwich()");
    yCenter = y;     xCenter = oldSphere.xCenter; class Bread {   }
    zCenter = z;     yCenter = oldSphere.yCenter;   Bread() { }
  }     zCenter = oldSphere.yCenter;     System.out.println("Bread()");
  Sphere(int theRadius, double x, doubl  }}   } public class MainClass {
e y, double z) { 5. 2. 6. Class Initializer: during }   public static void main(String[] args) {
    this(x, y, z); declaration     new Sandwich();
    radius = theRadius; // ClassInitializer2.java class Cheese {   }
  }   Cheese() { }
} class ClassInitializer2 {     System.out.println("Cheese()");
  static boolean bool = true;   } OUTPUT:
  static byte by = 20; } Meal()
5. 2. 5. Duplicating Objects using a   static char ch = 'X'; Lunch()
  static double d = 8.95; class Lettuce { PortableLunch()
Constructor
  static float f = 2.1f;   Lettuce() { Bread()
class Sphere {
  static int i = 63;     System.out.println("Lettuce()"); Cheese()
  int radius = 0;
Lettuce()   void f1(float x) {     System.out.println("f4(char)");
Sandwich() 5. 5. 3. Pass long parameters to     System.out.println("f1(float)");   }
overloading method   }   void f4(byte x) {
5. 3. 2. Passing Objects to a Method public class MainClass {   void f1(double x) {     System.out.println("f4(byte)");
class Sphere {     System.out.println("f1(double)");   }
  public int printNumber(int i) {
  double radius; // Radius of a sphere   }   void f4(short x) {
      return i*2;
  Sphere() {   void f2(char x) {     System.out.println("f4(short)");
  }
  }     System.out.println("f2(char)");   }
  }   void f4(int x) {
  public long printNumber(long i) {
  // Class constructor   void f2(byte x) {     System.out.println("f4(int)");
      return i*3;
  Sphere(double theRadius) {     System.out.println("f2(byte)");   }
  }
    radius = theRadius; // Set the radius   }   void f5(char x) {
  public static void main(String[] args) {
  }   void f2(short x) {     System.out.println("f5(char)");
}     System.out.println("f2(short)");   }
  }
  }   void f5(byte x) {
public class MainClass {   void f2(int x) {     System.out.println("f5(byte)");
}
  public static void main(String[] arg){     System.out.println("f2(int)");   }
    Sphere sp = new Sphere();   }   void f5(short x) {
printNumber(3) will invoke this method:
     public int printNumber(int i)   void f2(long x) {     System.out.println("f5(short)");
    aMethod(sp); To call the second, pass a long:     System.out.println("f2(long)");   }
  } printNumber(3L);   }   void f6(char x) {
     void f2(float x) {     System.out.println("f6(char)");
  private static void aMethod(Sphere sp){     System.out.println("f2(float)");   }
    System.out.println(sp); 5. 5. 4. Primitives and overloading   }   void f6(byte x) {
  } public class MainClass {   void f3(char x) {     System.out.println("f6(byte)");
}   void f1(char x) {     System.out.println("f3(char)");   }
    System.out.println("f1(char)");   }   void f7(char x) {
  }   void f3(byte x) {     System.out.println("f7(char)");
5. 3. 3. Returning From a Method   void f1(byte x) {     System.out.println("f3(byte)");   }
    System.out.println("f1(byte)");   }   void testDouble() {
public class MainClass {
  }   void f3(short x) {     double x = 0;
  private int aField;
  void f1(short x) {     System.out.println("f3(short)");     System.out.println("double argument:");
    System.out.println("f1(short)");   }     f1(x);
  public void aMethod() {
  }   void f3(int x) {     f2((float) x);
  void f1(int x) {     System.out.println("f3(int)");     f3((long) x);
  }
    System.out.println("f1(int)");   }     f4((int) x);
  public double volume() {
  }   void f3(long x) {     f5((short) x);
    return 50;
  void f1(long x) {     System.out.println("f3(long)");     f6((byte) x);
  }
    System.out.println("f1(long)");   }     f7((char) x);
}
  }   void f4(char x) {   }
  public static void main(String[] args) { 5. 5. 6. Demonstration of both Tree is 0 feet tall     Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 
    MainClass p = new MainClass(); constructor and ordinary method overloaded method: Tree is 0 feet tall 5.5, 6.6, 7.7 };
    p.testDouble(); Planting a seedling     Character[] characterArray = { 'H', 'E', 'L', '
overloading
  } L', 'O' };
class MyClass {
}
  int height;
5. 5. 7. Using overloaded methods     System.out.println("Array integerArray co
OUTPUT: to print array of different types ntains:");
  MyClass() {
double argument:     printArray(integerArray); // pass an Intege
    System.out.println("Planting a seedling"); public class MainClass {
f1(double) r array
    height = 0;   // method printArray to print Integer array
f2(float)     System.out.println("\nArray doubleArray c
  }   public static void printArray(Integer[] input
f3(long) ontains:");
Array) {
f4(int)     printArray(doubleArray); // pass a Double 
  MyClass(int i) {     // display array elements
f5(short) array
    System.out.println("Creating new Tree tha     for (Integer element : inputArray)
f6(byte)     System.out.println("\nArray characterArra
t is " + i + " feet tall");       System.out.printf("%s ", element);
f7(char) y contains:");
    height = i;     System.out.println();
    printArray(characterArray); // pass a Char
  }   }
acter array
  // method printArray to print Double array
5. 5. 5. Overloading based on the   }
  void info() {   public static void printArray(Double[] input
order of the arguments }
    System.out.println("Tree is " + height + " f Array) {
public class MainClass { eet tall");     // display array elements
  static void print(String s, int i) {   }     for (Double element : inputArray)
    System.out.println("String: " + s + ", int: "        System.out.printf("%s ", element); 5. 5. 8. Methods with differing type
+ i);   void info(String s) {     System.out.println(); signatures are overloaded - not
  }     System.out.println(s + ": Tree is " + height    } overridden.
+ " feet tall"); class A {
  static void print(int i, String s) {   }   // method printArray to print Character arr   int i, j;
    System.out.println("int: " + i + ", String: " +  } ay
s);   public static void printArray(Character[] in   A(int a, int b) {
  } public class MainClass { putArray) {     i = a;
  public static void main(String[] args) {     // display array elements     j = b;
  public static void main(String[] args) {     MyClass t = new MyClass(0);     for (Character element : inputArray)   }
    print("String first", 11);     t.info();       System.out.printf("%s ", element);
    print(99, "Int first");     t.info("overloaded method");   void show() {
  }     // Overloaded constructor:     System.out.println();     System.out.println("i and j: " + i + " " + j);
}     new MyClass();   }   }
  } }
OUTPUT: }   public static void main(String args[]) {
String: String first, int: 11     // create arrays of Integer, Double and Ch class B extends A {
int: 99, String: Int first OUTPUT: aracter   int k;
Creating new Tree that is 0 feet tall     Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
  B(int a, int b, int c) {     k = c; class Point {   }
    super(a, b);   }   public int x;
    k = c;   public static void main(String[] args) {
  }   void show() {   public int y;     Letter x = new Letter();
    System.out.println("k: " + k); }     x.c = 'a';
  void show(String msg) {   }     System.out.println("1: x.c: " + x.c);
    System.out.println(msg + k); } public class MainClass {     f(x);
  }   public static void increment(int x) {     System.out.println("2: x.c: " + x.c);
} class Override {     x++;   }
  public static void main(String args[]) {   } }
class Override {     B subOb = new B(1, 2, 3); OUTPUT:
  public static void main(String args[]) {   public static void reset(Point point) { 1: x.c: a
    B subOb = new B(1, 2, 3);     subOb.show(); // this calls show() in B     point.x = 0; 2: x.c: z
  }     point.y = 0;
    subOb.show("This is k: "); // this calls sho }   }
w() in B 5. 7. 4. Use an array to pass a
    subOb.show(); // this calls show() in A   public static void main(String[] args) { variable number of arguments to a
  } 5. 7. 1. By Value or By Reference     int a = 9;
method. This is the old-style
} 1. Primitive variables are passed by     increment(a);
    System.out.println(a); // prints 9 approach to variable-length
value.
5. 6. 1. Method overriding Demo 2. reference variables are passed by     Point p = new Point(); arguments.
class A { reference.     p.x = 400; class PassArray {
  int i, j; 3. When you pass a primitive variable,     p.y = 600;   static void vaTest(int v[]) {
the JVM will copy the value of the     reset(p);     System.out.print("Number of args: " + v.le
  A(int a, int b) { passed-in variable to a new local     System.out.println(p.x); // prints 0 ngth + " Contents: ");
    i = a; variable.   }
    j = b; 4. If you change the value of the local }     for (int x : v)
  } variable, the change will not affect OUTPUT:       System.out.print(x + " ");
the passed in primitive variable. 9
  // display i and j 5. If you pass a reference variable, the 0     System.out.println();
  void show() { local variable will refer to the same   }
    System.out.println("i and j: " + i + " " + j); object as the passed in reference
  } variable. 5. 7. 3. Passing objects to methods   public static void main(String args[]) {
} 6. If you change the object referenced class Letter {     int n1[] = { 10 };
within your method, the change   char c;     int n2[] = { 1, 2, 3 };
class B extends A { will also be reflected in the calling }     int n3[] = {};
  int k; code.
public class MainClass {     vaTest(n1); // 1 arg
  B(int a, int b, int c) {   static void f(Letter y) {     vaTest(n2); // 3 args
    super(a, b); 5. 7. 2. Reference Passing Test     y.c = 'z';     vaTest(n3); // no args
  }   }
}     public int value() { }     public int value() {
      return i;       return i;
    }     }
5. 8. 1. Returning Objects   } 5. 14. 3. Creating a new nested   }
class Test { object outside
  int a;   class B {   class B {
class Outside {
    private String label;     private String label;
  public class Inside {
  Test(int i) {   }
    a = i;     B(String whereTo) {     B(String whereTo) {
  }       label = whereTo;       label = whereTo;
  public Outside() {
    }     }
    Inside inner = new Inside();
  Test incrByTen() {
    Test temp = new Test(a + 10);     String readLabel() {     String readLabel() {
    return temp;       return label;       return label;
    
  }     }     }
  }
}   }   }
}

class ReturnObjectTest {   public static void main(String[] args) {   // Using inner classes looks just like


  public static void main(String args[]) {     MainClass p = new MainClass();   // using any other class, within MainClass:
5. 14. 4. Static Nested Classes
    Test ob1 = new Test(2);     // Must use instance of outer class   public void ship(String dest) {
public class Outside {
    Test ob2;     // to create an instances of the inner class     A c = new A();
  public static class Skinside {
:     B d = new B(dest);
  }
    ob2 = ob1.incrByTen();     MainClass.A c = p.new A();     System.out.println(d.readLabel());
  public class Inside {
    System.out.println("ob1.a: " + ob1.a);     MainClass.B d = p.new B("A");   }
  }
    System.out.println("ob2.a: " + ob2.a);   }
}
}   public static void main(String[] args) {
    ob2 = ob2.incrByTen();     MainClass p = new MainClass();
public class MainClass {
    System.out.println("ob2.a after second inc     p.ship("AAA");
  public static void main(String[] arg) {
rease: " + ob2.a); 5. 14. 2. Nested Classes   }
    Outside.Skinside example = new Outside.S
  } class Outside { }
kinside();
}
  }
  public class Inside { 5. 14. 6. Defining references to inner
}
  } classes
} public class MainClass {
5. 14. 1. Creating instances of inner   class A {
5. 14. 5. Creating inner classes
public class MainClass {     private int i = 11;
classes public class MainClass {
  public static void main(String[] arg) {
public class MainClass {   class A {
    Outside outer = new Outside();     public int value() {
  class A {     private int i = 11;
    Outside.Inside inner = outer.new Inside();       return i;
    private int i = 11;
    } 5. 14. 7. Nesting a class within a         }       label = whereTo;
  } method     }
        String getSlip() {
public class MainClass {
  class B {           return id;     public String readLabel() {
  public A dest(String s) {
    private String label;         }       return label;
    class B implements A {
      }     }
      private String label;
    B(String whereTo) {       A ts = new A("slip");
      label = whereTo;       String s = ts.getSlip();     // Nested classes can contain other static 
      private B(String whereTo) {
    }     } elements:
        label = whereTo;
    // Can't use it here! Out of scope:     public static void f() {
      }
    String readLabel() {     // ! A ts = new A("x");     }
      return label;   }
      public String readLabel() {
    }     static int x = 10;
        return label;
  }   public void track() {
      }
    method(true);     static class InnerInnerClass {
    }
  public B to(String s) {   }       public static void f() {
    return new B(s);
    return new B(s);       }
  }
  }   public static void main(String[] args) {
    MainClass p = new MainClass();       static int x = 10;
  public static void main(String[] args) {
  public A cont() {     p.track();     }
    MainClass p = new MainClass();
    return new A();   }   }
    A d = p.dest("A");
  } }
  }
  public static B dest(String s) {
}
  public void ship(String dest) {     return new ClassB(s);
    A c = cont(); 5. 14. 9. Nested classes (static inner   }
interface A {
    B d = to(dest); classes)
  String readLabel();
    System.out.println(d.readLabel());   public static A cont() {
} public class MainClass {
  }     return new ClassA();
  private static class ClassA implements A {
  }
    private int i = 11;
  public static void main(String[] args) {
5. 14. 8. Nesting a class within a
    MainClass p = new MainClass();   public static void main(String[] args) {
scope.     public int value() {
    p.ship("A");     A c = cont();
      return i;
    MainClass q = new MainClass(); public class MainClass {     B d = dest("A");
    }
  private void method(boolean b) {   }
  }
    MainClass.A c = q.cont();     if (b) { }
    MainClass.B d = q.to("A");       class A {
  protected static class ClassB implements B 
  }         private String id; interface A {
{
}   int value();
    private String label;
        A(String s) { }
          id = s;
    private ClassB(String whereTo) {
interface B { }         g();
  String readLabel();         f(); class ClassA implements InterfaceA {
} class X implements A, B {       }   private int i = 0;
}     }
  }   public void increment() {
5. 14. 10. An inner class cannot be class Y implements A { }     i++;
overriden like a method   B makeB() {     System.out.println(i);
    // Anonymous inner class: public class MainClass {   }
class A {
    return new B() {   public static void main(String[] args) { }
  private InnerA y;
    };     MyClass a = new MyClass();
  protected class InnerA {
  }     MyClass.A innerA = a.new A(); class ClassB {
    public InnerA() { System.out.println("A.Inn
}     MyClass.A.B innerb = innerA.new B();   void increment() {
erA()"); }
    innerb.h();     System.out.println("Other operation");
  }
public class MainClass {   }   }
  public A() {
  static void takesA(A a) { }
    System.out.println("New A()");
  }   static void f(ClassB mi) {
    y = new InnerA();
    mi.increment();
  }
  static void takesB(B b) { 5. 22. 5. Deriving a Class   }
}
  } class Animal { }
class B extends A {   public Animal(String aType) {
  public static void main(String[] args) {     type = aType; class ClassC extends ClassB {
  public class InnerB {
    X x = new X();   }   private int i = 0;
    public InnerB() { System.out.println("B.Inn
    Y y = new Y();   public String toString() {
erB()"); }
    takesA(x);     return "This is a " + type;   private void incr() {
  }
    takesA(y);   }     i++;
}
    takesB(x);   private String type;     System.out.println(i);
    takesB(y.makeB()); }   }
public class MainClass{
  } class Dog extends Animal {
  public static void main(String[] args) {
}   public Dog(String name){   private class Closure implements Interface
    new B();
    super(name); A {
  }
  }     public void increment() {
}
5. 14. 12. Nested classes can access   private String breed;       incr();
all members of all levels of the }     }
  }
5. 14. 11. Two ways that a class can classes they are nested within
implement multiple interfaces class MyClass {
5. 14. 14. Using inner classes for   InterfaceA getCallbackReference() {
interface A {   private void f() {}
    return new Closure();
}   class A { callbacks
  }
    private void g() {} interface InterfaceA {
}
interface B {     public class B {   void increment();
      void h() { }
class Caller {   protected class ClassA implements A { interface Counter { 4. The new class is called a child class
  private InterfaceA callbackReference;     private String label;   int next(); or a subclass or a derived class of
} the parent.
  Caller(InterfaceA cbh) {     private ClassA(String whereTo) { 5. The process of extending a class in
    callbackReference = cbh;       label = whereTo; public class MainClass{ object-oriented programming is
  }     }    called inheritance.
  private int count = 0; 6. In a subclass you can add new
  void go() {     public String readLabel() {   Counter getCounter(final String name) { methods and new fields as well as
    callbackReference.increment();       return label;     // A local inner class: override existing methods in the
  }     }     class LocalCounter implements Counter { parent class to change their
}   }       public LocalCounter() { behaviors.
        // Local inner class can have a construct 7. Inheritance gives you the
public class MainClass {   public A dest(String s) { or opportunity to add some
  public static void main(String[] args) {     return new ClassA(s);         System.out.println("LocalCounter()"); functionality that does not exist in
    ClassA c1 = new ClassA();   }       } the original class.
    ClassC c2 = new ClassC();       public int next() { 8. Inheritance can also change the
    ClassB.f(c2);   public B cont() {         System.out.print(name); // Access local  behaviors of the existing class to
    Caller caller1 = new Caller(c1);     return new ClassB(); final better suit your needs.
    Caller caller2 = new Caller(c2.getCallbackR   }         return count++; 9. The subclass and the superclass has
eference()); }       } an "is-a" relationship.
    caller1.go();     }
    caller1.go(); public class MainClass {     return new LocalCounter();
    caller2.go();   public static void main(String[] args) {   } 5. 22. 2. Accessibility
    caller2.go();     MyClass p = new MyClass(); Within a subclass you can access its
  }     B c = p.cont();    superclass's public and protected methods
}     A d = p.dest("A");   public static void main(String[] args) { and fields , but not the superclass's private
  }     MainClass lic = new MainClass(); methods. If the subclass and the superclass
}     Counter c1 = lic.getCounter("Local inner ") are in the same package, you can also access
; the superclass's default methods and fields.
5. 14. 15. Returning a reference to interface B {   }
an inner class   int value(); } public class P {
}   public void publicMethod() {
class MyClass {
  private class ClassB implements B {   }
interface A { 5. 22. 1. Inheritance
    private int i = 11;
  String readLabel(); 1. You extend a class by creating a   protected void protectedMethod() {
} new class.   }
    public int value() {
      return i; 2. The former and the latter will then
    } have a parent-child relationship.   void defaultMethod() {
  } 5. 14. 18. Local inner class can have 3. The original class is the parent class   }
a constructor or the base class or the superclass. }
constructor by using the super   private String breed;
class C extends P { keyword. }
  public void testMethod() { 2. 'super' must be the first statement
    publicMethod(); in the constructor. 5. 22. 8. Overriding a Base Class
    protectedMethod(); class Parent { Method
    defaultMethod();        public Parent(){
        class Animal {
  }
       }   public Animal(String aType) {
}
     }     type = new String(aType);
  }
     public class Child extends Parent {   public String toString() {
5. 22. 3. Method Overriding          public Child () {     return "This is a " + type;
1. When you extends a class, you can            super();   }
change the behavior of a method in          }   private String type;
     }
the parent class. }
2. This is called method overriding. class Dog extends Animal {
3. This happens when you write in a   public Dog(String aName) {
5. 22. 7. Derived Class Constructors:
subclass a method that has the     super("Dog");
same signature as a method in the Calling the Base Class Constructor     name = aName; 
parent class. class Animal {
    breed = "Unknown";
4. If only the name is the same but   public Animal(String aType) {
  }
the list of arguments is not, then it     type = new String(aType);   public Dog(String aName, String aBreed) {
is method overloading.   }
    super("Dog"); 
  public String toString() {
    name = aName;
    return "This is a " + type;
    breed = aBreed;
5. 22. 4. The extends Keyword   }
  }
  private String type;
You extend a class by using the extends keyword in a class declaration,   public String toString() {
The Parent class }
    return "It's " + name + " the " + breed;
public class Parent { class Dog extends Animal { 5. 22. 10. Inheritance, constructors
  }
  public Dog(String aName) {
     }   private String name;  and arguments
The Child class     super("Dog"); 
  private String breed; class A {
public class Child extends Parent {     name = aName; 
}   A(int i) {
     }     breed = "Unknown"; 
    System.out.println("A constructor");
  }
  }
  public Dog(String aName, String aBreed) {
}
    super("Dog"); 
5. 22. 6. The keyword super
    name = aName;
represents an instance of the direct     breed = aBreed; class B extends A {
  B(int i) {
superclass of the current object.   }
    super(i);
1. You can explicitly call the parent's   private String name; 
    System.out.println("B constructor");
constructor from a subclass's
  }
} doh(B)
}
class C extends B {
  C() { 5. 22. 14. Cleanup and inheritance
    super(11); 5. 22. 13. Overloading a base-class class Characteristic {
    System.out.println("C constructor"); method name in a derived class   private String s;
  }
does not hide the base-class
}   Characteristic(String s) {
versions.
    this.s = s;
public class MainClass { class A {
    System.out.println("Creating Characteristi
  public static void main(String[] args) {   char doh(char c) {
c " + s);
    C x = new C();     System.out.println("doh(char)");
  }
  }     return 'd';
}   }
  protected void dispose() {
  float doh(float f) {
    System.out.println("finalizing Characteristi
OUTPUT:     System.out.println("doh(float)");
c " + s);
A constructor     return 1.0f;
  }
B constructor   }
}
C constructor }
class Description {
5. 22. 12. Inheritance and upcasting. class B {}   private String s;
class A {
class C extends A {
  public void play() {   Description(String s) {
  void doh(B m) {
  }     this.s = s;
    System.out.println("doh(B)");
    System.out.println("Creating Description " 
  }
  static void tune(A i) { + s);
}
    i.play();   }
  }
public class MainClass {
}   protected void dispose() {
  public static void main(String[] args) {
    System.out.println("finalizing Description 
    C b = new C();
// Wind objects are instruments " + s);
    b.doh(1);
// because they have the same interface:   }
    b.doh('x');
class B extends A { }
    b.doh(1.0f);
}
    b.doh(new B());
class LivingCreature {
  }
public class MainClass {   private Characteristic p = new Characteristi
}
  public static void main(String[] args) { c("is alive");
doh(float)
    B flute = new B();
doh(char)
    A.tune(flute); // Upcasting   private Description t = new Description("Ba
doh(float)
  } sic Living Creature");
    System.out.println("Amphibian()"); OUTPUT:     depth = ob.depth;
  LivingCreature() {   } Creating Characteristic is alive   }
    System.out.println("LivingCreature()"); Creating Description Basic Living Creature
  }   protected void dispose() { LivingCreature()   Box(double w, double h, double d) {
    System.out.println("Amphibian dispose"); Creating Characteristic has heart     width = w;
  protected void dispose() {     t.dispose(); Creating Description Animal not Vegetable     height = h;
    System.out.println("LivingCreature dispos     p.dispose(); Animal()     depth = d;
e");     super.dispose(); Creating Characteristic can live in water   }
    t.dispose();   } Creating Description Both water and land
    p.dispose(); } Amphibian()   Box() {
  } Creating Characteristic Croaks     width = -1; // use -1 to indicate
} class Frog extends Amphibian { Creating Description Eats Bugs     height = -1; // an uninitialized
  private Characteristic p = new Characteristi Frog()     depth = -1; // box
class Animal extends LivingCreature { c("Croaks"); Bye!   }
  private Characteristic p = new Characteristi Frog dispose
c("has heart");   private Description t = new Description("Ea finalizing Description Eats Bugs   Box(double len) {
ts Bugs"); finalizing Characteristic Croaks     width = height = depth = len;
  private Description t = new Description("A Amphibian dispose   }
nimal not Vegetable");   public Frog() { finalizing Description Both water and land
    System.out.println("Frog()"); finalizing Characteristic can live in water   double volume() {
  Animal() {   } Animal dispose     return width * height * depth;
    System.out.println("Animal()"); finalizing Description Animal not Vegetable   }
  }   protected void dispose() { finalizing Characteristic has heart }
    System.out.println("Frog dispose"); LivingCreature dispose
  protected void dispose() {     t.dispose(); finalizing Description Basic Living Creature class BoxWeight extends Box {
    System.out.println("Animal dispose");     p.dispose(); finalizing Characteristic is alive   double weight; // weight of box
    t.dispose();     super.dispose();
    p.dispose();   }   BoxWeight(BoxWeight ob) { // pass object t
    super.dispose(); } 5. 22. 15. Creating a Multilevel o constructor
  } Hierarchy     super(ob);
} public class MainClass {     weight = ob.weight;
class Box {
  }
  private double width;
class Amphibian extends Animal {   public static void main(String[] args) {
  private Characteristic p = new Characteristi     Frog frog = new Frog();   BoxWeight(double w, double h, double d, 
  private double height;
c("can live in water");     System.out.println("Bye!"); double m) {
    frog.dispose();     super(w, h, d); // call superclass construct
  private double depth;
  private Description t = new Description("B   } or
oth water and land");     weight = m;
  Box(Box ob) { // pass object to constructor
}   }
    width = ob.width;
  Amphibian() {
    height = ob.height;
  BoxWeight() {   public static void main(String args[]) {     System.out.println("Inside B's constructor. class UseSuper {
    super();     Shipment shipment1 = new Shipment(10,  ");   public static void main(String args[]) {
    weight = -1; 20, 15, 10, 3.41);   }     B subOb = new B(1, 2);
  }     Shipment shipment2 = new Shipment(2, 3 }
, 4, 0.76, 1.28);     subOb.show();
  BoxWeight(double len, double m) { class C extends B {   }
    super(len);     double vol;   C() { }
    weight = m;     System.out.println("Inside C's constructor.
  }     vol = shipment1.volume(); ");
}     System.out.println("Volume of shipment1    } Overloaded constructor
is " + vol); } public class Point {
class Shipment extends BoxWeight {     System.out.println("Weight of shipment1 i   int x, y;
  double cost; s " + shipment1.weight); class CallingCons {
    System.out.println("Shipping cost: $" + shi   public static void main(String args[]) {   Point(int x, int y) // Overloaded constructor
  Shipment(Shipment ob) { // pass object to c pment1.cost);     C c = new C();   {
onstructor     System.out.println();   }     this.x = x;
    super(ob); }     this.y = y;
    cost = ob.cost;     vol = shipment2.volume();   }
  }     System.out.println("Volume of shipment2 
is " + vol); 5. 23. 1. Variable in subclass hides   Point(Point p) // Overloaded constructor
  Shipment(double w, double h, double d, d     System.out.println("Weight of shipment2 i the variable in the super class   {
ouble m, double c) { s " + shipment2.weight);     this(p.x, p.y);
class A {
    super(w, h, d, m); // call superclass constr     System.out.println("Shipping cost: $" + shi   } // Calls the first constructor
  int i;
uctor pment2.cost);
}
    cost = c;   }   void move(int dx, int dy) {
  } }     x += dx;
class B extends A {
  int i; // this i hides the i in A     y += dy;
  Shipment() {   }
    super(); 5. 22. 16. Demonstrate when   B(int a, int b) {
    cost = -1; constructors are called in a   public String toString() {
    super.i = a; // i in A
  }     return "(" + x + ", " + y + ")";
Multilevel Hierarchy     i = b; // i in B
  }   }
class A {
  Shipment(double len, double m, double c)  }
  A() {
{   
    System.out.println("Inside A's constructor.   void show() {
    super(len, m);
");     System.out.println("i in superclass: " + sup
    cost = c; Overloading based on the order of
  } er.i);
  }
}     System.out.println("i in subclass: " + i); the arguments
}
  } public class OverloadingOrder {
class B extends A { }
class DemoShipment {
  B() {   static void print(String s, int i) {
    System.out.println("String: " + s + ", int: "  }   } Your choice:
+ i); class Dog extends Animal {   public String toString() { This is a Duck
  }   public Dog(String aType){     return super.toString() + "\nIt's " + name  It's E the F
   super(aType);  + " the " + breed; Quack quackquack
  static void print(int i, String s) {   }   } Your choice:
    System.out.println("int: " + i + ", String: " +    public void sound() {   public void sound() { This is a Duck
s);     System.out.println("Woof Woof");     System.out.println("Quack quackquack"); It's E the F
  }   }   } Quack quackquack
}   private String name;
  public static void main(String[] args) { class Cat extends Animal {   private String breed;
    print("String first", 11);   public Cat(String aName) { } 5. 24. 2. An example of polymorphism
    print(99, "Int first");     super("Cat");  public class MainClass { class Employee {
  }     name = aName;    public static void main(String[] args) {   public void work() {
}     breed = "Unknown";      Animal[] theAnimals = { new Dog("A"),      System.out.println("I am an employee.");
  }                             new Cat("C", "D"),   }
  public Cat(String aName, String aBreed) {                             new Duck("E", "F") }; }
5. 24. 1. Polymorphism     super("Cat");      Animal petChoice;
It means the ability of a single variable of a     name = aName;      Random select = new Random(); class Manager extends Employee {
given type to be used to reference objects     breed = aBreed;      for (int i = 0; i < 5; i++) {   public void work() {
of different types and to automatically call   }       petChoice = theAnimals[select.nextInt(th     System.out.println("I am a manager.");
the method that is specific to the type of   public String toString() { eAnimals.length)];   }
object the variable references. (Ivor     return super.toString() + "\nIt's " + name        System.out.println("\nYour choice:\n" + 
Horton's Beginning Java 2, JDK 5 Edition by + " the " + breed; petChoice);   public void manage() {
Ivor Horton Wrox Press 2005 )   }       petChoice.sound();     System.out.println("Managing ...");
polymorphism works with derived class   public void sound() {     }   }
objects.     System.out.println("Miiaooww");   } }
  } }
import java.util.Random;   private String name; public class PolymorphismTest1 {
class Animal {   private String breed; OUTPUT:   public static void main(String[] args) {
  public Animal(String aType) { } Your choice:     Employee employee;
    type = new String(aType); class Duck extends Animal { This is a A     employee = new Manager();
  }   public Duck(String aName) { Woof Woof     System.out.println(employee.getClass().ge
  public String toString() {     super("Duck");  Your choice: tName());
    return "This is a " + type;     name = aName;  This is a Duck     employee.work();
  }     breed = "Unknown"; It's E the F     Manager manager = (Manager) employee;
  public void sound(){   } Quack quackquack     manager.manage();
    System.out.println("Sound for an animal")   public Duck(String aName, String aBreed) { Your choice:   }
;     super("Duck");  This is a Duck }
  }     name = aName;  It's E the F
  private String type;     breed = aBreed; Quack quackquack
5. 24. 3. Downcasting and Run-Time Glyph() after draw()     r.callme(); // calls C's version of callme
Type Identification (RTTI) RoundGlyph.RoundGlyph(), radius = 5   }
class Useful { 5. 24. 4. Constructors and }
  public void f() { polymorphism don't produce what you
  } might expect 5. 24. 5. Dynamic Method Dispatch
abstract class Glyph { class A { 5. 24. 6. Using run-time polymorphism.
  public void g() {   abstract void draw();   void callme() { class Figure {
  }     System.out.println("Inside A's callme met   double dim1;
}   Glyph() { hod");
    System.out.println("Glyph() before draw()   }   double dim2;
class MoreUseful extends Useful { "); }
  public void f() {     draw();   Figure(double a, double b) {
  }     System.out.println("Glyph() after draw()"); class B extends A {     dim1 = a;
  }   void callme() {     dim2 = b;
  public void g() { }     System.out.println("Inside B's callme met   }
  } hod");
class RoundGlyph extends Glyph {   }   double area() {
  public void u() {   private int radius = 1; }     System.out.println("Area for Figure is und
  } efined.");
  RoundGlyph(int r) { class C extends A {     return 0;
  public void v() {     radius = r;   void callme() {   }
  }     System.out.println("RoundGlyph.RoundGl     System.out.println("Inside C's callme met }
yph(), radius = " + radius); hod");
  public void w() {   }   } class Rectangle extends Figure {
  } }   Rectangle(double a, double b) {
}   void draw() {     super(a, b);
    System.out.println("RoundGlyph.draw(), r class Dispatch {   }
public class MainClass { adius = " + radius);   public static void main(String args[]) {
  public static void main(String[] args) {   }     A a = new A(); // object of type A   // override area for rectangle
    Useful[] x = { new Useful(), new MoreUsef }     B b = new B(); // object of type B   double area() {
ul() };     C c = new C(); // object of type C     System.out.println("Inside Area for Rectan
    x[0].f(); public class MainClass {     A r; // obtain a reference of type A gle.");
    x[1].g();   public static void main(String[] args) {     return dim1 * dim2;
    new RoundGlyph(5);     r = a; // r refers to an A object   }
    // x[1].u();   }     r.callme(); // calls A's version of callme }
    ((MoreUseful) x[1]).u(); // Downcast/RTTI }
    ((MoreUseful) x[0]).u(); // Exception thro     r = b; // r refers to a B object class Triangle extends Figure {
wn OUTPUT:     r.callme(); // calls B's version of callme   Triangle(double a, double b) {
  } Glyph() before draw()     super(a, b);
} RoundGlyph.draw(), radius = 0     r = c; // r refers to a C object   }
}   Triangle(double a, double b) {
  // override area for right triangle public abstract class DefaultPrinter {     super(a, b);
  double area() {   public String toString() { class AbstractDemo {   }
    System.out.println("Inside Area for Triangl     return "Use this to print documents.";   public static void main(String args[]) {
e.");   }     B b = new B();   double area() {
    return dim1 * dim2 / 2;     System.out.println("Inside Area for Triangl
  }   public abstract void print(Object docu     b.callme(); e.");
} ment);     b.callmetoo();     return dim1 * dim2 / 2;
}   }   }
class FindAreas { } }
  public static void main(String args[]) { 1. The toString method has an
    Figure f = new Figure(10, 10); implementation, so you do not need to class AbstractAreas {
    Rectangle r = new Rectangle(9, 5); override this method. 5. 28. 3. Using abstract methods and   public static void main(String args[]) {
    Triangle t = new Triangle(10, 8); 2. The print method is declared abstract classes.     Rectangle r = new Rectangle(9, 5);
and does not have a body. abstract class Figure {     Triangle t = new Triangle(10, 8);
    Figure figref;   double dim1;     Figure figref;
public class MyPrinter extends DefaultPrint
    figref = r; er {   double dim2;     figref = r;
    System.out.println("Area is " + figref.area(   public void print(Object document) {     System.out.println("Area is " + figref.area(
));     System.out.println("Printing document");   Figure(double a, double b) { ));
    // some code here     dim1 = a;
    figref = t;   }     dim2 = b;     figref = t;
    System.out.println("Area is " + figref.area( }   }     System.out.println("Area is " + figref.area(
)); ));
  abstract double area();   }
    figref = f; 5. 28. 2. A demonstration of abstract. } }
    System.out.println("Area is " + figref.area( abstract class A {
));   abstract void callme(); class Rectangle extends Figure {
  }   Rectangle(double a, double b) { 5. 29. 1. Interfaces and Abstract Classes
}   void callmetoo() {     super(a, b); 1. The interface should be regarded as a
    System.out.println("This is a concrete met   } contract between a service provider
hod."); and its clients.
5. 28. 1. Abstract Classes   }   double area() { 2. An abstract class is a class that cannot
1. Provide a contract between a service }     System.out.println("Inside Area for Rectan be instantiated
provider and its clients. gle."); 3. An abstract class must be implemented
2. An abstract class can provide class B extends A {     return dim1 * dim2; by a subclass.
implementation.   void callme() {   } 4. In Java, the interface is a type.
3. To make an abstract method, use the     System.out.println("B's implementation of  } Follow this format to write an interface:
abstract modifier in front of the method callme.");
declaration.   } class Triangle extends Figure {
accessModifier interface interfaceName { An inner class to an interface will be static
} 1. An implementation class has to override 5. 29. 7. Interfaces and Polymorphism: and public by default.
all methods in the interface. Using Multiple Interfaces
public interface Printable { 2. A class can implement multiple interface ThisInterface { interface Port {
         void print (Object o); interfaces.   public void thisMethod();   // Methods & Constants declared in the int
} } erface...

1. The Printable interface has a method, 5. 29. 4. A Partial Interface interface ThatInterface {   class Info {
print. Implementation   public void thatMethod();     // Definition of the class...
2. print is public even though there is no interface Conversions { }   }
public keyword.   double INCH_TO_MM = 25.4; }
  double OUNCE_TO_GRAM = 28.349523125 class MyClass implements ThisInterface, Tha
; tInterface { public class MainClass {
5. 29. 2. Fields and Methods in an   double POUND_TO_GRAM = 453.5924;   // Class definition including methods from    public static void main(String[] a) {
Interface double HP_TO_WATT = 745.7; both interfaces...     Port.Info info = new Port.Info();
1. Fields in an interface must be initialized   double WATT_TO_HP= 1.0 / HP_TO_WATT;   public void thisMethod() {   }
and are implicitly public, static, and   public double inchesToMillimeters(double      System.out.println("this"); }
final. inches);   }
2. You declare methods in an interface   public double ouncesToGrams(double oun
just as you would in a class. ces);   public void thatMethod() { 5. 29. 9. Encapsulating Constants in a
3. Methods in an interface do not have a }     System.out.println("that"); Program
body.   } interface ConversionFactors {
4. All methods are implicitly public and }   double INCH_TO_MM = 25.4;
abstract 5. 29. 5. Extending Interfaces
interface ConversionFactors { public class MainClass {   double OUNCE_TO_GRAM = 28.349523125
interface Conversions{   double INCH_TO_MM = 25.4;   public static void main(String[] a) { ;
  double inchesToMillimeters(double inches) }     MyClass cls = new MyClass();
; interface Conversions extends ConversionFa     cls.thisMethod();   double POUND_TO_GRAM = 453.5924;
} ctors {     cls.thatMethod();
double inchesToMillimeters(double inches);   }   double HP_TO_WATT = 745.7;
} }
5. 29. 3. To implement an interface: use   double WATT_TO_HP = 1.0 / HP_TO_WATT
the implements keyword after the class OUTPUT: ;
declaration 5. 29. 6. Interfaces and Multiple this }
public class CanonDriver implements Printa Inheritance that ---
ble { interface HisInterface {} public class MainClass {
         public void print (Object obj) { interface HerInterface {}   public static void main(String[] a) {
             // code that does the printing public interface MyInterface extends HisInt 5. 29. 8. Nesting Classes in an Interface     System.out.println(ConversionFactors.INC
         } erface, HerInterface {} Definition H_TO_MM);
}
  }   }   long randomLong = rand.nextLong() * 10; erface);
}   float randomFloat = rand.nextLong() * 10;   }
  public static void v(C x) {   double randomDouble = rand.nextDouble()  }
OUTPUT:     x.cMethod(); * 10;
25.4   } }
7. 2. 4. If a class object is an interface or
  public static void w(ClassA x) { a class
5. 29. 10. Multiple interfaces     x.aMethod(); 7. 2. 1. The superclass of interfaces is public class Main {
interface A {   } always null   public static void main(String[] args) {
  void aMethod(); public class Main {     // Checking whether Cloneable is an interf
}   public static void main(String[] args) {   public static void main(String[] argv) throw ace or class
    D h = new D(); s Exception {     Class clazz = Cloneable.class;
interface B {     t(h);     boolean isInterface = clazz.isInterface();
  void bMethod();     u(h);     Class cls = java.lang.Cloneable.class;     System.out.println("Is Interface = " + isInt
}     v(h);     Class sup = cls.getSuperclass(); // null erface);
    w(h);   }   }
interface C {   } }
  void cMethod(); }
} 7. 2. 5. Listing the Interfaces That a
7. 2. 2. Listing the Interfaces That an Class Implements
class ClassA { 5. 29. 11. Initializing interface fields Interface Extends public class Main {
  public void aMethod() { with non-constant initializers public class Main {   public static void main(String[] argv) throw
  } import java.util.Random;   public static void main(String[] argv) throw s Exception {
} s Exception {     Class cls = java.lang.String.class;
public class MainClass {     Class cls = java.util.List.class;     Class[] intfs = cls.getInterfaces();
class D extends ClassA implements A, B, C {   public static void main(String[] args) {     Class[] intfs = cls.getInterfaces(); // java.u
  public void bMethod() {     System.out.println(RandVals.randomInt); til.Collection   }
  }     System.out.println(RandVals.randomLong }
);   }
  public void cMethod() {     System.out.println(RandVals.randomFloat
  } ); 7. 2. 6. Although the type of o2 is an
}     System.out.println(RandVals.randomDoub 7. 2. 3. Checking whether String is an interface, getSuperclass() returns the
le);
interface or class object's superclass
public class MainClass {   }
public class Main { public class Main {
  public static void t(A x) { }
  public static void main(String[] argv) throw   public static void main(String[] argv) throw
    x.aMethod();
s Exception { s Exception {
  }
interface RandVals {
    Class clazz = String.class;     Runnable o2 = new Runnable() {
  public static void u(B x) {   Random rand = new Random();
    boolean isInterface = clazz.isInterface();       public void run() {
    x.bMethod();   int randomInt = rand.nextInt(10);
    System.out.println("Is Interface = " + isInt       }
    };
    Class sup = o2.getClass().getSuperclass(); /
/ java.lang.Object
  }
}

7. 2. 7. The interfaces for a primitive


type is an empty array
public class Main {
  public static void main(String[] argv) throw
s Exception {

    Class cls = int.class;
    Class[] intfs = cls.getInterfaces(); // []

  }
}

S-ar putea să vă placă și