【问题标题】:Do I avoid the risk of privacy leaks, if I set the instance variables to private?如果我将实例变量设置为私有,是否可以避免隐私泄露的风险?
【发布时间】:2021-11-16 03:24:34
【问题描述】:

我正在处理一项 Java 作业。我的教授写道:警告:一定要设置类的属性以避免任何隐私泄露的风险。我对此感到困惑。我对隐私泄露的理解总是使用复制构造函数,但是实例变量如何泄露隐私呢?这就是我们总是将实例变量设置为私有的原因吗?

【问题讨论】:

  • 你(和你的教授)对“隐私泄露”这个词是什么意思?\

标签: java computer-science


【解决方案1】:

这是DemoClass中的一个例子,变量是私有的,不能直接访问。只能通过 getter 和 setter 获取这些变量

public class DemoClass {
    // you can not get these variable directly
        private String stringValue;
        private int integerValue;
    
        public DemoClass(String stringValue, int integerValue) {
            this.stringValue = stringValue;
            this.integerValue = integerValue;
        }
    
        public void setStringValue(String stringValue) {
            this.stringValue = stringValue;
        }
    
        public void setIntegerValue(int integerValue) {
            this.integerValue = integerValue;
        }
    
        public String getStringValue() {
            return stringValue;
        }
    
        public int getIntegerValue() {
            return integerValue;
        }
    }


    class Main {
      public static void main(String[] args) {
            DemoClass demoClass =new  DemoClass("My String Value",120);
            System.out.println(demoClass.getIntegerValue());
            System.out.println(demoClass.getStringValue());
      }
    
    }

【讨论】:

    【解决方案2】:

    如果这是您的主要代码,那么答案是肯定的,这就是我们将除全局变量之外的任何变量设置为私有的原因。

    class Demo {
      private String Var = "100";
      void Meth(String str) {
        System.out.println(str + Var);
      }
    }
    class Main {
      public static void main(String[] args) {
        Demo demo1 = new Demo();
        demo1.Meth("10 x 10 = ");
        System.out.println(demo1.Var);//Error. This variable is set to private so it cannot be accessed.
      }
    
    }
    

    您的变量的隐私或控制只能由变量的超类/控制块访问。

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多