抽象类就是说的一个概念,他不能实例化,而子类则必须将抽象类的方法重新定义,否则,子类本身也就成为一个抽象类。
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>Preferences>Java>Code Generation>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);
}
}