Java/Language Basics/Interface and Abstract Class — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:47, 1 июня 2010

Abstract classes and methods

// : c07:PrivateOverride.java
// Abstract classes and methods.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class PrivateOverride {
  private void f() {
    System.out.println("private f()");
  }
  public static void main(String[] args) {
    PrivateOverride po = new Derived();
    po.f();
  }
}
class Derived extends PrivateOverride {
  public void f() {
    System.out.println("public f()");
  }
} ///:~





Extending an interface with inheritance

// : c08:HorrorShow.java
// Extending an interface with inheritance.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
interface Monster {
  void menace();
}
interface DangerousMonster extends Monster {
  void destroy();
}
interface Lethal {
  void kill();
}
class DragonZilla implements DangerousMonster {
  public void menace() {
  }
  public void destroy() {
  }
}
interface Vampire extends DangerousMonster, Lethal {
  void drinkBlood();
}
class VeryBadVampire implements Vampire {
  public void menace() {
  }
  public void destroy() {
  }
  public void kill() {
  }
  public void drinkBlood() {
  }
}
public class HorrorShow {
  static void u(Monster b) {
    b.menace();
  }
  static void v(DangerousMonster d) {
    d.menace();
    d.destroy();
  }
  static void w(Lethal l) {
    l.kill();
  }
  public static void main(String[] args) {
    DangerousMonster barney = new DragonZilla();
    u(barney);
    v(barney);
    Vampire vlad = new VeryBadVampire();
    u(vlad);
    v(vlad);
    w(vlad);
  }
} ///:~





Find out whether interfaces are inherited

/** Find out whether interfaces are inherited.
 * Start with Thread which implements Runnable.
 */
public class InterfaceInherit extends Thread {
  public static void main(String[] a) {
    new InterfaceInherit().start();
  }
  public void run() {
    if (this instanceof InterfaceInherit)
    System.out.println("This is InterfaceInherit");
    if (this instanceof Thread)
    System.out.println("This is Thread");
    if (this instanceof Runnable)
    System.out.println("This is Thread -- Interfaces ARE inherited!");
  }
}





Holds a sequence of Objects

// : c08:Sequence.java
// Holds a sequence of Objects.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
interface Selector {
  boolean end();
  Object current();
  void next();
}
public class Sequence {
  private Object[] objects;
  private int next = 0;
  public Sequence(int size) {
    objects = new Object[size];
  }
  public void add(Object x) {
    if (next < objects.length)
      objects[next++] = x;
  }
  private class SSelector implements Selector {
    private int i = 0;
    public boolean end() {
      return i == objects.length;
    }
    public Object current() {
      return objects[i];
    }
    public void next() {
      if (i < objects.length)
        i++;
    }
  }
  public Selector getSelector() {
    return new SSelector();
  }
  public static void main(String[] args) {
    Sequence sequence = new Sequence(10);
    for (int i = 0; i < 10; i++)
      sequence.add(Integer.toString(i));
    Selector selector = sequence.getSelector();
    while (!selector.end()) {
      System.out.println(selector.current());
      selector.next();
    }
  }
} ///:~





Implement multiple interfaces

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

interface I1 {
  abstract void test(int i);
}
interface I2 {
  abstract void test(String s);
}
/**
 * To show what happens to the possible conflicts if you 
 * implement multiple interfaces: there are no conflicts.
 * If multiple interfaces have the exact same method, you
 * merely have to implement it.
 * If multiple interfaces have similar methods, you must
 * implement them all.
 * There"s still no conflict.
 */
public class MultInterfaces implements I1, I2 {
  public void test(int i) {
    System.out.println("In MultInterfaces.I1.test");
  }
  public void test(String s) {
    System.out.println("In MultInterfaces.I2.test");
  }
  public static void main(String[] a) {
    MultInterfaces t = new MultInterfaces();
    t.test(42);
    t.test("Hello");
  }
}





Initializing interface fields with non-constant initializers

// : c08:RandVals.java
// Initializing interface fields with non-constant initializers.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.Random;
public interface RandVals {
  Random rand = new Random();
  int randomInt = rand.nextInt(10);
  long randomLong = rand.nextLong() * 10;
  float randomFloat = rand.nextLong() * 10;
  double randomDouble = rand.nextDouble() * 10;
} ///:~





Interface Collision

// : c08:InterfaceCollision.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
interface I1 {
  void f();
}
interface I2 {
  int f(int i);
}
interface I3 {
  int f();
}
class C {
  public int f() {
    return 1;
  }
}
class C2 implements I1, I2 {
  public void f() {
  }
  public int f(int i) {
    return 1;
  } // overloaded
}
class C3 extends C implements I2 {
  public int f(int i) {
    return 1;
  } // overloaded
}
class C4 extends C implements I3 {
  // Identical, no problem:
  public int f() {
    return 1;
  }
}
// Methods differ only by return type:
//! class C5 extends C implements I1 {}
//! interface I4 extends I1, I3 {} ///:~





Interface Usage Example

interface Act {
  void act();
}
class Actor1 implements Act {
  public void act() {
    System.out.println("To be, or not to be");
  }
}
class Actor2 implements Act {
  public void act() {
    System.out.println("Wherefore art thou Romeo?");
  }
}
public class TryOut {
  public static void main(String args[]) {
    Actor1 hamlet = new Actor1();
    Actor2 juliet = new Actor2();
    tryout(hamlet);
    tryout(juliet);
  }
  private static void tryout(Act actor) {
    actor.act();
  }
}





Multiple interfaces

// : c08:Adventure.java
// Multiple interfaces.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
interface CanFight {
  void fight();
}
interface CanSwim {
  void swim();
}
interface CanFly {
  void fly();
}
class ActionCharacter {
  public void fight() {
  }
}
class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly {
  public void swim() {
  }
  public void fly() {
  }
}
public class Adventure {
  public static void t(CanFight x) {
    x.fight();
  }
  public static void u(CanSwim x) {
    x.swim();
  }
  public static void v(CanFly x) {
    x.fly();
  }
  public static void w(ActionCharacter x) {
    x.fight();
  }
  public static void main(String[] args) {
    Hero h = new Hero();
    t(h); // Treat it as a CanFight
    u(h); // Treat it as a CanSwim
    v(h); // Treat it as a CanFly
    w(h); // Treat it as an ActionCharacter
  }
} ///:~





Multi Super Interfaces

public class MultiSuperInterfaces {
  public interface Marker extends java.io.Serializable, java.rmi.Remote,
      java.lang.Runnable {
  }
  public class Marked implements Marker {
    public void run() {
      // needed for Runnable
    }
  }
  public static void main(String[] args) {
    new MultiSuperInterfaces().print();
  }
  void print() {
    Object o = new Marked();
    if (o instanceof java.io.Serializable) {
      System.out.println("Is Serializable");
    }
    if (o instanceof java.rmi.Remote) {
      System.out.println("Is Remote");
    }
    if (o instanceof java.lang.Runnable) {
      System.out.println("Is Runnable");
    }
  }
}





This shows that a class implementing an interface need not

import java.io.*;
/** This shows that a class implementing an interface need not
 * declare all the Throws that are declared in the interface.
 */
public class InterfaceWithoutAllThrows {
  interface bar {
    public void foo() throws IOException;
  }
  class baz implements bar {
    public void foo() {
      System.out.println("This is foo-lish");
    }
  }
  public static void main(String[] argv) {
    new InterfaceWithoutAllThrows().new baz().foo();
  }
}





Two ways that a class can implement multiple interfaces

// : c08:MultiInterfaces.java
// Two ways that a class can implement multiple interfaces.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
interface A {
}
interface B {
}
class X implements A, B {
}
class Y implements A {
  B makeB() {
    // Anonymous inner class:
    return new B() {
    };
  }
}
public class MultiInterfaces {
  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());
  }
} ///:~