简体   繁体   English

为什么我可以在其类之外更改私有属性?

[英]Why can I change a private attribute out of its class?

I code on Processing for a few months now and I'm trying to use java classes. 我现在在Processing上编写代码已有几个月,而我正在尝试使用Java类。 I'm a newbie on java classes and I believe that private attributes of a class cannot be modified outside this class. 我是Java类的新手,我相信不能在此类之外修改类的私有属性。 However I did change a private attribute of an object in Processing's setup() void. 但是我确实在Processing的setup() void中更改了对象的私有属性。 I don't understand why I am able to do that. 我不明白为什么我能做到这一点。 Can anybody help me ? 有谁能够帮助我 ?

A part of the class code: 类代码的一部分:

public class Character {
  private String name;
  ...

  public Character(String pName, ...) {
    name = pName;
    ...

  public void dname() {
    println(this.name);
  }
}

The setup() code: setup()代码:

void setup() {
  player = new Character("John Doe", ...);
  player.dname();  //I get "John Doe".
  player.name = "tara"; 
  player.dname();  //I get "tara", without any error.
}

Thank you very much ! 非常感谢你 !

If this is in the Processing editor, then Java classes are inner classes behind the scenes. 如果在Processing编辑器中,则Java类是幕后的内部类

This is why you can access private variables in the class from your sketch. 这就是为什么您可以从草图访问类中的私有变量的原因。 This is also why you can access Processing functions from inside your class. 这也是为什么您可以从类内部访问Processing函数的原因。

You could try putting the class in its own tab. 您可以尝试将类放在自己的标签中。 Make sure the tab ends with .java , so it's treated as a "real" Java class. 确保选项卡以.java结尾,因此将其视为“真实” Java类。

But Processing tends to hide stuff like access modifiers from you, so you might be best off just not worrying about it too much. 但是Processing往往会向您隐藏诸如访问修饰符之类的内容,因此最好不要担心太多。

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

相关问题 为什么我可以更改class中的私有属性? - Why can I change the private attribute in the class? 为什么如果我将其默认构造函数声明为private,则无法将其子类化 - why a class can not be subclassed if i declare its default constructor as private 为什么要在Java中使用getter设置私有类属性的值? - Why can I set the value of a private class attribute with getter in Java? Java:为什么我可以读取私有属性? - Java: Why can i read a private attribute? 一个类可以有自己的专用PrintWriter吗? - Can a class have its own private PrintWriter? 为什么我不能将这个 (SectionsPagerAdapter) 类设为私有? - Why can't I make this (SectionsPagerAdapter) class private? 为什么我可以访问封闭类引用的私有成员 - Why can I access the private members of an enclosing class reference 为什么我可以从 Class 外部访问私有变量? - Why Can I Access Private Variable From Outside Class? 为什么可以通过这种方式访问​​私有变量时无法访问基类的私有字段 - Why I can not access private field of a base class when private variables can be accessed this way 为什么一个类的实例可以访问它自己类型的另一个实例的私有字段? - Why can an instance of a class access private fields of another instance of its own type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM