gpt4 book ai didi

java - 访问继承的类成员时出错

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:45 25 4
gpt4 key购买 nike

我是java初学者。我想使用基类和派生类的对象访问基类中扩展(继承类的数据成员)。但我面临以下错误: token “bonus”上存在语法错误,当尝试使用基类和派生类的对象访问成员奖金时,在此 token 之后预期存在 VariableDeclaratorId

如果我将对象创建和访问的代码放在 public static void main 方法中,这个错误就会消失。我想了解一下这是为什么?

public class DerivedClass{
public int bonus = 100;
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}
class BaseClass extends DerivedClass
{
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
b.bonus = 200; //error here
d.bonus = 400; //error here
System.out.println("bonus this year is:"+" "+ s.bonus);
}

错误消息:

Syntax error on token "bonus", VariableDeclaratorId expected after this token

最佳答案

将其包装在一个方法中,您将看到两者都有效。不允许您直接在类主体中编写代码块。

class BaseClass extends DerivedClass {    
public static void main(String[] args) {
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
b.bonus = 200;
d.bonus = 400;
}
}

initialisers ,但它们也必须在 {} 内声明。

{
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
b.bonus = 200;
d.bonus = 400;
}

类体具有定义良好的结构(字段声明、方法声明、 block 声明)。您只需遵循该结构即可。

8.1.6. Class Body and Member Declarations

A class body may contain declarations of members of the class, that is, fields (§8.3), methods (§8.4), classes (§8.5), and interfaces (§8.5).

A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.

ClassBody:
{ {ClassBodyDeclaration} }

ClassBodyDeclaration:
ClassMemberDeclaration
InstanceInitializer
StaticInitializer
ConstructorDeclaration

ClassMemberDeclaration:
FieldDeclaration
MethodDeclaration
ClassDeclaration
InterfaceDeclaration
;

关于java - 访问继承的类成员时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57472690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com