LX【468x60】


インターフェイス



コード

//定数を定義するインターフェイス

interface Type{
	int nTypeA = 1;	
	int nTypeB = 2;	
	int nTypeC = 3;	
	
	String sTypeA = new String("TypeA");
	String sTypeB = new String("TypeB");
	String sTypeC = new String("TypeC");
}

//メソッドを宣言したインターフェイス

interface IntType{
	void	putIntType(int Type);
	int	getIntType();
}

interface StringType{
	void	putStringType(String Type);
	String	getStringType();
}

//インターフェイスを継承
interface IntStrType extends IntType, StringType{
	
}

//抽象クラス
abstract class Cls{
	int nType;
	String sType;	
}

//インターフェイス(IntType)を参照
class IntClsA extends Cls implements IntType{
	
	public void	putIntType(int Type){
		this.nType = Type;
	}
	
	public int	getIntType(){
		return nType;
	}
}

//インターフェイス(StringType)を参照
class StringClsB extends Cls implements StringType{
	
	public void	putStringType(String Type){
		this.sType = Type;
	}
	
	public String	getStringType(){
		return sType;
	}
}

//インターフェイス(IntType,StringType)を参照
//class ClsC extends Cls implements IntType, StringType{
class ClsC extends Cls implements IntStrType{	
	public void	putIntType(int Type){
		this.nType = Type;
	}
	
	public int	getIntType(){
		return nType;
	}
	
	public void	putStringType(String Type){
		this.sType = Type;
	}
	
	public String	getStringType(){
		return sType;
	}
	
}


//
public class TestInterface {

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

		//
		System.out.println("------------------------");
		
		IntClsA A = new IntClsA();
		A.putIntType(Type.nTypeA);		//定数を定義するインターフェイス(Type)を代入
		System.out.println("A -> " + A.getIntType());
		
		StringClsB B = new StringClsB();
		B.putStringType(Type.sTypeB);	//定数を定義するインターフェイス(Type)を代入
		System.out.println("B -> " + B.getStringType());
		
		ClsC C = new ClsC();
		C.putIntType(Type.nTypeC);		//定数を定義するインターフェイス(Type)を代入
		C.putStringType(Type.sTypeC);	//定数を定義するインターフェイス(Type)を代入
		System.out.println("C -> " + C.getIntType());
		System.out.println("C -> " + C.getStringType());
		System.out.println("");	
		
		
		//instanceof演算子
		Cls Obj[] = new Cls[5];
		
		Obj[0] = new IntClsA();
		Obj[1] = new StringClsB();
		Obj[2] = new ClsC();
		Obj[3] = new IntClsA();
		Obj[4] = new StringClsB();
		
		//インターフェイス(IntType)を含んでいる場合に表示
		for(int i = 0; i < 5; i++){
			if(Obj[i] instanceof IntType){
				Class ClsBuff = Obj[i].getClass();
				System.out.println(i + " -> " + ClsBuff.getName());
			}
		}
		
		//
		System.out.println("------------------------");
		
		System.out.println("End");
		
	}
}
			


結果

Start
------------------------
A -> 1
B -> TypeB
C -> 3
C -> TypeC

0 -> IntClsA
2 -> ClsC
3 -> IntClsA
------------------------
End
			

 


<戻る>