簡體   English   中英

當我的類實例不應該為空值時,為什么會得到空值?

[英]Why do I get null values for my instance of a class when they are not supposed to be null?

我這里有三節課:

abstract class ParentClass{
    String ide;
    ArrayList args;
    ParentClass from_type;
    ParentClass to_type;
}

class Classone extends ParentClass{
    String ide;
    ArrayList<ParentClass> args;

    public Classone(ParentClass from_type, ParentClass to_type){
        this.from_type = from_type;
        this.to_type = to_type;
    }

    public Classone(String ide, ArrayList<ParentClass> args){
        this.ide = ide;
        this.args = args;
    }

    @Override
    public String toString() {
        String result = "";
        if (ide == null) {
            return from_type.toString() + " -> " + to_type.toString();
        }
        else {
            if (args.size() == 0) {
            return ide;
            }
            else if (args.size() == 2) {
                result = args.get(0).toString() + " " + ide + " " + args.get(1).toString();
                return result;
                }
                else {
                    return "Wrong number";
                    }
        }
    }
}

class Classtwo extends Classone{
    ParentClass from_type;
    ParentClass to_type;

    public Classtwo(ParentClass from_type, ParentClass to_type){
        super(from_type, to_type);
    }
}

當我創建如下的實例時:

sameType方法在下面:

public static boolean sameType(ParentClass t1, ParentClass t2){
    if (t1 instanceof Classone && t2 instanceof Classone) {
        if (t1.ide != null && t2.ide != null) {
            System.out.println(t1.ide);
            System.out.println(t2.ide);
            return t1.ide == t2.ide;
        }
        else {
            return false;
        }
    }
    else {
        return false;
    }
}

Classone a = new Classone("bool", new ArrayList<ParentClass>());
Classone b = new Classone("bool", new ArrayList<ParentClass>());
System.out.println(sameType(a,b));

它會打印false ,然后再打印其他內容,因此這意味着此處的a.ideb.idenull 他們應該是弦bool ; 有人可以幫我嗎?

我認為這是因為ParentClass和Classone都具有一個名為“ ide”的屬性,並且在sameType方法中,您正在訪問未初始化的parent的ide屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM