302班

java突击队
posts - 151, comments - 74, trackbacks - 0, articles - 14
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

interface实例

Posted on 2007-06-15 19:26 停留的风 阅读(279) 评论(0)  编辑  收藏
抽象类就是说的一个概念,他不能实例化,而子类则必须将抽象类的方法重新定义,否则,子类本身也就成为一个抽象类。
interface内所有的方法都是public,所有的成员变量都是public static final,即使你没有申明。interface里的值必须是在编译的时候确定。

例一.

public interface Shape {

void draw() {}

void erase() {}

}

class Circle extends Shape {

void draw() {

System.out.println("Circle.draw()");

}

void erase() {

System.out.println("Circle.erase()");

}

}

class Square extends Shape {

void draw() {

System.out.println("Square.draw()");

}

void erase() {

System.out.println("Square.erase()");

}

}

class Triangle extends Shape {

void draw() {

System.out.println("Triangle.draw()");

}

void erase() {

System.out.println("Triangle.erase()");

}

}

public class Shapes {

public static Shape randShape() {

switch((int)(Math.random() * 3)) {

default: // To quiet the compiler

case 0: return new Circle();

case 1: return new Square();

case 2: return new Triangle();

}

}

public static void main(String[] args) {

Shape[] s = new Shape[9];

// Fill up the array with shapes:

for(int i = 0; i < s.length; i++)

s[i] = randShape();

// Make polymorphic method calls:

for(int i = 0; i < s.length; i++)

s[i].draw();

}

}

例二.

public interface print {

public void println();

}

//--------------------------------------------------------------

package com.exaple;

/**

* @author liu yu

*

* To change the template for this generated type comment go to

* Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments

*/

class A implements print{

int a = 3;

public void println(){

System.out.println("The value of Class A : "+a);

}

}

 

class B implements print{

int b = 4;

public void println(){

System.out.println("The value of Class B : "+b);

}

}

 

public class MyInterfaceDemo {

 

public static void dosomething(print c){

c.println();

}

public static void main(String [] args){

A a1 = new A();

B b1 = new B();

MyInterfaceDemo.dosomething(a1);

MyInterfaceDemo.dosomething(b1);

}

}


只有注册用户登录后才能发表评论。


网站导航: