简体   繁体   English

我可以从未被子类覆盖的方法内部访问子对象的字段吗?

[英]Can I have access to a field of a child object from inside a method which is not overridden by the child class?

I am trying to implement the "Space Challenge" program in java. 我正在尝试在Java中实现“太空挑战”程序。

See EDIT at the bottom for more clarity 请参阅底部的“编辑”以获得更清晰的说明

The instructions ask you to write a Class Rocket and child classes U1 and U2. 说明要求您编写Class Rocket以及子类U1和U2。

The child classes have fields specific to these, being rocketWeight and maxWeight. 子类具有特定于这些字段的字段,即rocketWeight和maxWeight。 Their values have to be different for each of the child classes. 对于每个子类,它们的值都必须不同。

The parent class Rocket has a method canCarry which needs to check the weight of the rocket. 父类Rocket具有canCarry方法,该方法需要检查火箭的重量。 This method is inherited by U1 and U2 but NOT overridden. 此方法由U1和U2继承,但不会被覆盖。

Then I call the canCarry method, eg u1.canCarry(arguments), the method inside itself looks at the variable this.rocketWeight and this.maxWeight, but I have checked that instead of having the value u1.rocketWeight and u1.maxWeight (as I would like them to have), they have value 0. 然后,我调用canCarry方法,例如u1.canCarry(arguments),其内部的方法将查看变量this.rocketWeight和this.maxWeight,但我已经检查了它是否具有值u1.rocketWeight和u1.maxWeight(as我希望他们拥有),它们的值为0。

I think my problem is that I don't know how to have access to a variable from a child object from inside a method of the parent class. 我认为我的问题是我不知道如何从父类的方法内部的子对象访问变量。

This is the call to the method. 这是对方法的调用。 The object u1 is of class U1, which is a child class of Rocket: 对象u1属于类U1,它是Rocket的子类:

u1.canCarry(itemList.get(i))

itemList.get(i) is an object that has a field weight itemList.get(i)是一个具有字段权重的对象

This is the method itself, which is declared inside the class Rocket: 这是方法本身,在类Rocket中声明:

@Override
public boolean canCarry(Item item) {
    return ((this.weightRocket + item.weight) < this.maxWeight);
}

If I print this.weightRocket and this.maxWeight inside the method, both are 0. Outside the method both have the expected value. 如果我在方法内部打印this.weightRocket和this.maxWeight,则均为0。在方法外部都具有预期值。 item.weight also has the value I would expect. item.weight也具有我期望的值。

I'm sure this is very basic stuff, I just started with java one week ago. 我确定这是非常基本的东西,一周前我才刚开始使用Java。

Thanks 谢谢

EDIT: a comment below let me know that there's not enough code so I took a look at best practices for asking questions. 编辑:下面的评论让我知道没有足够的代码,所以我看了提出问题的最佳实践。

The next code snippets show a simplified version of what I'm trying to do. 下一段代码片段显示了我要执行的操作的简化版本。

Rocket.java: contains one method canCarry Rocket.java:包含一种方法canCarry

public class Rocket {

    int maxWeight;

    boolean canCarry(int itemWeight){
        return itemWeight < this.maxWeight;
    }

}

U1.java: sets the value of maxWeight for an object of this child class U1.java:为此子类的对象设置maxWeight的值

public class U1 extends Rocket {

    int maxWeight = 18;

}

U2.java: same as U1 U2.java:与U1相同

public class U2 extends Rocket{

    int maxWeight = 23;

}

Main.java: calls canCarry method for objects of class U1 and U2. Main.java:为类U1和U2的对象调用canCarry方法。 I would like that the value maxWeight inside the method canCarry is the one defined in the children classes, but it uses the one in the parent class, despite that the objects u1 and u2 are of class U1 and U2. 我想方法canCarry内的值maxWeight是在子类中定义的值,但是它使用父类中的值,尽管对象u1和u2属于类U1和U2。

public class Main {

    public static void main(String[] args) {

        int itemWeight = 20;

        U1 u1 = new U1();
        U2 u2 = new U2();

        if(u1.canCarry(itemWeight)){
            System.out.println("Launch rocket 1!");
        } else {
            System.out.println("Rocket 1 can't launch");
        }

        if(u2.canCarry(itemWeight)){
            System.out.println("Launch rocket 2!");
        } else {
            System.out.println("Rocket 2 can't launch");
        }

    }
}

From the descriptin of the problem it looks like I'm supposed to do this. 从问题的描述看来,我应该这样做。

The problem: https://classroom.udacity.com/courses/ud283/lessons/2b5bc57f-de73-45a4-b3a7-8dcc8da2f178/concepts/b8b57dc5-2eb8-4834-8e96-4956fc322f50 问题: https : //classroom.udacity.com/courses/ud283/lessons/2b5bc57f-de73-45a4-b3a7-8dcc8da2f178/concepts/b8b57dc5-2eb8-4834-8e96-4956fc322f50

Verbatim: Create a class Rocket (...) carry and canCarry should be implemented here and will not need to be overridden in the U1 and U2 classes. 逐字记录:创建一个Rocket(...)携带类和canCarry应该在此处实现,并且在U1和U2类中无需重写。

Any idea how to deal with this? 知道如何处理吗?

Thanks 谢谢

EDIT: does it have something to do with creating constructors for each of the classes? 编辑:是否与为每个类创建构造函数有关? I didn't do it but I know that java creates a default constructor if you don't 我没有这样做,但我知道如果您不这样做,java会创建一个默认构造函数

I solved my own question. 我解决了自己的问题。 I had to give value to the fields in a constructor. 我必须给构造函数中的字段赋值。

This is the code that works as intended: 这是按预期工作的代码:

Rocket.java Rocket.java

public class Rocket {

    int maxWeight;

    Rocket(){
        maxWeight = 0;
    }

    boolean canCarry(int itemWeight){
        return itemWeight < this.maxWeight;
    }

}

U1.java: U1.java:

public class U1 extends Rocket {

    U1() {
        maxWeight = 18;
    }

}

U2.java: U2.java:

public class U2 extends Rocket{

    U2() {
        maxWeight = 23;
    }

}

Main.java: Main.java:

public class Main {

    public static void main(String[] args) {

        int itemWeight = 20;

        U1 u1 = new U1();
        U2 u2 = new U2();

        if(u1.canCarry(itemWeight)){
            System.out.println("Launch rocket 1!");
        } else {
            System.out.println("Rocket 1 can't launch");
        }

        if(u2.canCarry(itemWeight)){
            System.out.println("Launch rocket 2!");
        } else {
            System.out.println("Rocket 2 can't launch");
        }

    }
}

There is no (straightforward) way for a superclass method to access subclass fields or methods, but there's no need for that in your situation. 超类方法没有(直接)访问子类字段或方法的方法,但是在您所处的情况下则不需要这样做。

Your mistake is to introduce a new field maxWeight in eg your subclass U1 . 您的错误是在子类U1引入了新字段maxWeight This means that a U1 instance has two fields with the same name maxWeight , one only visible to methods in the Rocket class, and one only visible to methods in the U1 class. 这意味着一个U1实例具有两个具有相同名称maxWeight字段,一个字段仅对Rocket类中的方法可见,而一个字段仅对U1类中的方法可见。

You'd better only have one maxWeight field, visible to Rocket and to its subclasses, and initialize it differently in U1 and U2 . 最好只有一个maxWeight字段,对Rocket及其子类可见,并在U1U2对其进行不同的初始化 You can do that like this: 您可以这样做:

public class U1 extends Rocket {
    public U1() {
        maxWeight = 18;
    }
}
public class U2 extends Rocket {
    public U2() {
        maxWeight = 23;
    }
}

Then everything will work as expected. 然后一切都会按预期进行。

Make macWeight in the super class a protected Integer. 将超类中的macWeight设置为受保护的Integer。 In the sub classes set the value in a constrictor. 在子类中,在压缩器中设置值。

public u1 () {
      this.maxWeight = 18;
}

Etc. 等等。

Much more explicit, safer and will work. 更明确,更安全并且可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从具体子类中的重写方法访问通过抽象类中的构造函数实例化的对象的属性? - How to access the attributes of an object instantiated via a constructor in an abstract class, from an overridden method in a concrete child class? 如何在JAVA中从父类的内部类中调用子类中的重写方法? - How can I call the overridden method in a child class from a parent class's inner class in JAVA? 为什么在父类中必须强制有一个子方法以引用父类的引用来调用它,该父类引用子类的对象? - Why is it mandatory to have a child method in Parent class to call it with a reference of parent class which is referring to an object of child class? 有没有一种方法可以在子类上实现可以从子类访问属性的方法? - Is there a way to implement a method on a child class that I can access the attributes from it's child? 如何从子类调用重写的父类方法? - How do I call an overridden parent class method from a child class? 从另一个子类访问子方法 - Access a child method from another child class 访问覆盖子类的变量和方法时的区别 - Difference when overridden variable and method from child class are accessed 在静态工厂方法中使用覆盖方法创建实例时,如何访问封闭类中的私有字段? - How can I access private field in enclosing class when creating instance with overridden method in static factory method? 我怎样才能创建一个只能在子类内部调用访问的方法? - How can i make a method with call access only inside the child class? 如何在子方法中访问子类中的父类变量? - How to access parent class variable in child class inside a child method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM