如何使用超类

时间:2016-05-30 06:39:26

标签: java

我是java的初学者。这是我的代码

class Super{
public int a;
}
class sub extends Super{
int a = 10;
}

public class test{
public static void main(String args[]){

Super var = new sub();
System.out.println(var.a);//Here I want to print 10 , value of sub class
} 
}

是否可能,如果是,请告诉我如何? 我对这个问题的标题有一些问题,所以请建议我一个合适的,因为我已经在我的代码中解释了我想要的一切。

2 个答案:

答案 0 :(得分:1)

您应该为超类中的a添加getter方法

public int getA(){
return a;
}

子类也将继承getter,您可以访问子类中的a值。它也被重新命名为使class属性受保护或私有而不是公共。

答案 1 :(得分:0)

将变量设为私有,并在两个类中添加getA()方法,子类中的方法覆盖超类。

public class Foo
{
    static class Super{
        private int a;
        public int getA() { return a; }
    }

    static class Sub extends Super{
        private int a = 10;
        @Override
        public int getA() { return a; }
    }

    public static void main(String args[]) {
        Super sup1 = new Super();
        Super sup2 = new Sub();
        Sub   sub  = new Sub();
        System.out.println(sup1.getA());
        System.out.println(sup2.getA());
        System.out.println(sub.getA());
    } 
}

此输出

0
10
10
相关问题