public interface Square { double getSquare(int var1); }
public interface Sqrt { double getSqrt(int var1); }
public class A{ void p(Square square) { System.out.println(square.getSquare(3)); //【代码1】);//输出getSquare方法计算后的结果 } void k(Sqrt sqrt) { System.out.println(Math.sqrt(sqrt.getSqrt(0))); //【代码2】输出getSqrt方法计算后的结果 } }
public class Anonymity { public static void main(String args[]) { A a=new A(); a.p( new Square(){ @Override public double getSquare(int n) { return (int)Math.pow(n,2); } } ); //a.p();//【代码3】实现Square接口,重写getSquare方法,返回n的平方 Sqrt sqrt=new Sqrt(){ @Override public double getSqrt(int x) { return (double) Math.sqrt(x); } };//【代码4】重写getSqrt方法,返回x的开平方根,用静态Math.sqrt方法来运算 System.out.println("计算开平方:"+sqrt.getSqrt(18)); } }