importjava.util.Arrays;/***
*@authormdyb
* date: 2017/8/11
* file: ISuperImpl.java*/
public class ISuperImpl implementsISuper {public static voidmain(String[] args) {
ISuper iSuper= newISuperImpl();
iSuper.showClass();//无覆盖直接调用
System.out.println("\n====================");
ISuper iSuper2= newISuperImpl2();
iSuper2.showClass();//调用覆盖的方法
System.out.println("\n====================");
ISuper iSuper3= newISuperImpl3();
iSuper3.showClass();
System.out.println("\n====================");
ISuper iSuper31= newISuperImpl3();
ISuper iSuper21= newISuperImpl2();
ISuper iSuper11= newISuperImpl();
System.out.println("iSuper value = " +iSuper.getValue());
ISuper[] s= ISuper.filter(5000, iSuper, iSuper11, iSuper2, iSuper21, iSuper3, iSuper31);
ISuper[] s2= ISuper.filter(4000, iSuper, iSuper11, iSuper2, iSuper21, iSuper3, iSuper31);
Arrays.stream(s).forEach((a)-> System.out.print(a.getValue() + " "));
System.out.println();
Arrays.stream(s2).forEach((a)-> System.out.print(a.getValueRandom() + " "));
}private int value = (int) (Math.random() * 2000);
@Overridepublic intgetValueRandom() {return value + 3333;
}
@Overridepublic intgetValue() {returnvalue;
}
}class ISuperImpl2 implementsISuper {private int value = (int) (Math.random() * 777);//default 方法可以覆盖
@Overridepublic voidshowClass() {
System.out.println("before");
ISuper.super.showClass();
System.out.println("after");
}
@Overridepublic intgetValueRandom() {return (value + 2000) * 2;
}
@Overridepublic intgetValue() {returnvalue;
}
}class ISuperImpl3 implementsISuper {privateString status;private int value = (int) (3141 + Math.random() * 600);publicISuperImpl3() {
status= getClass().getName() +System.currentTimeMillis();
}
@Overridepublic voidshowClass() {
System.out.println("class status of calling this method: "+status + System.currentTimeMillis() + "\n" +Math.random());
}
@Overridepublic intgetValueRandom() {return (value + status.length() - (int) (1333 * Math.random())) / 2;
}
@Overridepublic intgetValue() {returnvalue;
}
}
本文展示了Java中多态的使用,包括如何通过ISuper接口实现不同子类(ISuperImpl2, ISuperImpl3)的方法覆盖和调用。代码示例演示了静态方法和非静态方法的调用,以及如何使用filter方法根据条件筛选对象数组并打印其值。
1万+

被折叠的 条评论
为什么被折叠?



