java中静态内部类的范围

时间:2016-07-28 09:32:45

标签: java static-methods inner-classes

我今天发现了一件非常奇怪的事情。我有以下带有静态内部类的类。

public class PDto {

private Agreement agreement = new Agreement();

    public static class Agreement{
        public String agreementName;
        public String agreementDescription;
        public String currency;
    }

    public Agreement getAgreement() {
        return agreement;
    }

    public void setAgreement(Agreement agreement) {
        this.agreement = agreement;
    }
}

另一个ClassA类有以下方法: -

private Agreement createBillingAgreement(PDto payment) {

    PDto.Agreement billingAgreement = payment.getAgreement();
    Agreement agreement = new Agreement();
    agreement.setName(billingAgreement.agreementName);
    agreement.setDescription(billingAgreement.agreementDescription);
    billingAgreement.agreementName = "Changed agreeement Name" ;
}

B类调用A类方法的代码

classBService.createBillingAgreement(payment);
System.out.println("Changed billing agreement name : " + payment.getAgreement().agreementName);

当我从类ClassB打印协议名称时,我得到了在类A的createBillingAgreement方法中设置的值。这怎么可能。

1 个答案:

答案 0 :(得分:1)

静态内部类用于静态访问同一个类。例如:

EditText etSearch = (EditText) view.findViewById(R.id.etSearch);

etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = etSearch.getText().toString();
                if (str.isEmpty()) {
                    btnClear.setVisibility(View.INVISIBLE);
                } else {
                    btnClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

OUT:

嗨!来自AnotherClass

或者在你的情况下:

public class Parent{
    public static class Child{
        public void aMethod(String s){
            System.out.println("Hi!" + s);
        }
    }
}

public class AnotherClass{
    public void AnotherMethod(){
        Parent.Child.aMethod("From AnotherClass");
    }
}

这是静态类