Java嵌套类可见性规则

时间:2018-04-12 13:20:45

标签: java

访问下面对象n的字段other是否有一种不那么繁琐的方法?

public class NestedVisibility
{
    private int n = 42;

    public static class B extends NestedVisibility {
        public void foo(NestedVisibility guest) {
            super.n = 0; // OK
            guest.n = 0; // OK

            B other = new B();
            other.n = 0; // Compile-time error. Weird!
            ((NestedVisibility)other).n = 0; // OK
        }
    }
}

我不得不做更多的工作来访问other的私有字段而不是私有字段guest吗?

2 个答案:

答案 0 :(得分:1)

扩展类不会继承私有变量。您可以通过父类继承的getter和setter访问它们。

这是您重写的代码:

public class NestedVisibility
{
    private int n = 42;

    public int getN(){
        return this.n;
    }

    public void setN(int n){
        this.n = n;
    }

    public static class B extends NestedVisibility {
        public void foo(NestedVisibility guest) {
            super.n = 0; // OK
            guest.n = 0; // OK

            B other = new B();
            other.setN(0);
            console.log(other.getN());
        }
    }
}

所以基本上class B没有field n,但是超级NestedVisibilityThis post有更多关于此的信息,以及关于它的互联网中有很多随机博客。

您可以从嵌套类访问私有变量。如同,如果你创建一个类型为public class NestedVisibility { private int n = 42; public static class B extends NestedVisibility { public void foo(NestedVisibility guest) { super.n = 0; // OK guest.n = 0; // OK NestedVisibility other = new NestedVisibility(); other.n = 0; //OK } } } (不扩展)的对象,那么你可以在嵌套类中直接访问它,如下所示:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
@IonicPage()
@Component({
  selector: 'page-fashion',
  templateUrl: 'fashion.html',
})
export class FashionPage {
  users: any;
  body: Object = {
    "id": 1014,
    "filter": null,
    "lat": 13.05831,
    "lng": 80.21195,
    "mapRadius": 5,
    "pageSize": 50,
    "pageStart": 1,
    "priceRangeFrom": 0,
    "priceRangeTo": 100000
  };
  constructor(public navCtrl: NavController, public navParams: NavParams, public httpClient: HttpClient) {
    this.users = this.httpClient.post('myapi',this.body);
    this.users.subscribe(data => {
      this.users = data;
      console.log('my data: ', data);
      console.log("the users data ------------>",this.users);
    })
  }
}

希望这有助于清理事情。

答案 1 :(得分:0)

  

专用范围变量仅对其所属的类可见。


如果您希望扩展类并希望授予对类变量的访问权限,则应使用受保护的范围声明它。

public class NestedVisibility
{
  protected int n = 42;

  public static class B extends NestedVisibility {
    public void foo(NestedVisibility guest) {
      super.n = 0; // OK
      guest.n = 0; // OK

      B other = new B();
      other.n = 0; // now is OK
      ((NestedVisibility)other).n = 0; // OK
    }
  }
}