发生错误:类SubclassInSamePackage是public,应该在名为SubclassInSamePackage.java的文件中声明

时间:2017-06-05 10:14:37

标签: java

请帮我解决错误

的代码
class SubclassInSamePackage is public, should be declared in a file named SubclassInSamePackage.java

程序:

package pckage1;

class BaseClass {

    public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
private int getY() {
    return y;
}
private void setY(int y) {
    this.y = y;
}
protected int getZ() {
    return z;
}
protected void setZ(int z) {
    this.z = z;
}
int getA() {
    return a;
}
void setA(int a) {
    this.a = a;
}
}


public class SubclassInSamePackage extends BaseClass {

    public static void main(String args[]) {
    BaseClass rr = new BaseClass();
    rr.z = 0;
    SubclassInSamePackage subClassObj = new SubclassInSamePackage();
    //Access Modifiers - Public
    System.out.println("Value of x is : " + subClassObj.x);
    subClassObj.setX(20);
    System.out.println("Value of x is : " + subClassObj.x);
    //Access Modifiers - Public
    //      If we remove the comments it would result in a compilaton
    //      error as the fields and methods being accessed are private
    /*      System.out.println("Value of y is : "+subClassObj.y);

     subClassObj.setY(20);

     System.out.println("Value of y is : "+subClassObj.y);*/
    //Access Modifiers - Protected
    System.out.println("Value of z is : " + subClassObj.z);
    subClassObj.setZ(30);
    System.out.println("Value of z is : " + subClassObj.z);
    //Access Modifiers - Default
    System.out.println("Value of x is : " + subClassObj.a);
    subClassObj.setA(20);
    System.out.println("Value of x is : " + subClassObj.a);
    }
}

1 个答案:

答案 0 :(得分:0)

文件中只能有一个公共类,该类的名称应与文件名的名称相匹配。

如果要在同一文件中创建多个类,可以将它们标记为私有或“空白”但不公开。