2014-11-21 65 views
0

我创建了一个断言。基本上,我不知道将要验证什么。你可以给一个重写的例子吗?

它可以是文本(用户名)或数量(价格,可用产品的数量等)。

我已经创建了两个同名的方法,无论是参数的类型的基础上,它会被称为..

这是正确的实现重写的概念?

public class U_Assertion { 

    public void assertEquals(String actual, String expected) { 
     // Compare Actual and Expected 
     if (actual.equals(expected)) { 
      System.out.println(actual + " Meets Expected " + expected); 
     } else { 
      System.out.println(actual + " did not Meet Expected " + expected); 
     } 
    } 

    public void assertEquals(int actual, int expected) { 
     // Compare Actual and Expected 
     if (actual == expected) { 
      System.out.println(actual + " Meets Expected " + expected); 
     } else { 
      System.out.println(actual + " did not Meet Expected " + expected); 
     } 
    } 
} 

回答

0

这不是overriding,这是overloading

是的,这是一个正确的重载实现。

这让人想起System.out(一PrintStream对象)的方法,它有不同的print & println方法不同的数据类型,但做的价值观同样的事情。有关过载的另一个示例,请参见constructors of Scanner,该参数不仅用于参数类型以使用不同的输入源,而且在参数数量上过载,以使参数charsetName可选。 (请注意,在您的情况下使用重载不是必须的 - 两种方法中的参数数量相同,因此您可以通过使用参数类型为Object的其中一种方法获得相同的功能:

public void assertEquals(Object actual, Object expected) { 
    // Compare Actual and Expected 
    if (actual.equals(expected)) { 
     System.out.println(actual + " Meets Expected " + expected); 
    } else { 
     System.out.println(actual + " did not Meet Expected " + expected); 
    } 
} 

这将任意Object S,其中包括String工作。它也将努力为原始类型,如int,因为值将是boxedInteger对象,但有一个小的额外性能开销了这一点。用超载仍然有用,因为它避免了拳击开销。)

0

覆盖概念是重新定义父类的方法成子类:

public class ParentClass { 
    public void method() { 
     System.out.println("parent"); 
    } 
} 

public class ChildClass extends ParentClass{ 
    @Override 
    public void method() { 
     System.out.println("child"); 
    } 
} 

new ParentClass().method(); 
new ChildClass().method(); 

这将输出:

parent 
child 
相关问题