English 中文(简体)
Java(Beginner)可变遗产
原标题:Variable inheritance in Java (Beginner)

I have a class A with a variable bool var = true and a getter method getVar(). I m trying to create a class B that extends A and redefines var to bool var = false. The code:

public class A{
    protected boolean var = true;
    public boolean getVar(){
        return var;
    }
}

public class B extends A{
    protected boolean var = false;
}

问题是,如果我执行:

B b_class = new B();
System.out.println(b_class.getVar());

I obtain true and I don t undestand why. What I m doing wrong?

最佳回答

You shouldn t be creating a new instance variable in your overridden class, because it can t be seen by the super class (A), and therefore when getVar() is called, it will return the value it can see. You should instead be setting the value of var in the constructor to be what you want.

public B() {
    var = false;
}
问题回答

页: 1 仅躲藏在<代码>A.var上,但仅限于<代码>。 B。 您是getVar(), 一种载于A的方法,见A.var, 即true

您在<代码>B上宣布了一个新的<代码>var<>/code>领域,该代码为<代码>A.var。 相反:

public class B extends A {
    public B() {
        var = false;
    }
}

在超级类别中,可以选择的变数不能改变。 你们已经宣布保护养羊人。 因此,无论你在延长级别上做什么,都永远表明你是真实的。

在B等地,GetVar是甲型六氯环己烷的产物,在甲型六氯环己烷确实如此。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签