Java 构造函数调用必须是具有继承的构造函数中的第一条语句
我有我的父抽象JUnitTest类:Java 构造函数调用必须是具有继承的构造函数中的第一条语句,java,junit,constructor,junit4,super,Java,Junit,Constructor,Junit4,Super,我有我的父抽象JUnitTest类: public abstract class RestWSTest { public RestWSTest() { } @Before public void setUp() throws Exception { ... } @After public void tearDown() throws Exception { ... } } 然后,我希望有一个扩展restwest的类,如下所示:
public abstract class RestWSTest
{
public RestWSTest()
{
}
@Before
public void setUp() throws Exception
{
...
}
@After
public void tearDown() throws Exception
{
...
}
}
然后,我希望有一个扩展restwest
的类,如下所示:
public class RestWSCreateGroupTest extends RestWSTest
{
public RestWSCreateGroupTest()
{
super();
}
@Before
public void setUp() throws Exception
{
super(); --> *Constructor call must be the first statement in a constructor*
...
}
@After
public void tearDown() throws Exception
{
super(); --> *Constructor call must be the first statement in a constructor*
...
}
@Test
public void testCreateGroup()
{
...
}
}
为什么我会收到错误消息?我有一个构造函数,在那里我调用了
super()
,所以我真的不知道该怎么做…方法public void setUp()
不是构造函数。不能调用super()代码>在它里面。我想你打算super.setUp()
方法public void setUp()
不是构造函数。不能调用super()代码>在它里面。我想你打算super.setUp()代码>不能在构造函数方法之外使用super()调用。
换句话说,setUp()和tearDown()是方法,它们不是构造函数,所以不能使用super()调用
相反,您可以使用以下语法访问/调用超类方法:super.mySuperClassMethod()强>
因此,请按以下方式更改代码:
public class RestWSCreateGroupTest extends RestWSTest
{
public RestWSCreateGroupTest()
{
super();
}
@Before
public void setUp() throws Exception
{
super.setUp();
...
}
@After
public void tearDown() throws Exception
{
super.tearDown();
...
}
@Test
public void testCreateGroup()
{
...
}
}
有关更多详细信息,请参阅以下链接:
不能在构造函数方法之外使用super()调用。
换句话说,setUp()和tearDown()是方法,它们不是构造函数,所以不能使用super()调用
相反,您可以使用以下语法访问/调用超类方法:super.mySuperClassMethod()强>
因此,请按以下方式更改代码:
public class RestWSCreateGroupTest extends RestWSTest
{
public RestWSCreateGroupTest()
{
super();
}
@Before
public void setUp() throws Exception
{
super.setUp();
...
}
@After
public void tearDown() throws Exception
{
super.tearDown();
...
}
@Test
public void testCreateGroup()
{
...
}
}
有关更多详细信息,请参阅以下链接: