我不是一个PHP开发人员,所以我不知道如果PHP是比较流行的使用显式的getter/setter方法,在纯OOP的风格,与私人领域(我喜欢的方式):
class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($x) {
$this->firstField = $x;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($x) {
$this->secondField = $x;
}
}
Run Code Online (Sandbox Code Playgroud)
或只是公共领域:
class MyClass {
public $firstField;
public $secondField;
}
Run Code Online (Sandbox Code Playgroud)
谢谢
采访者:什么是封装,你如何用Java实现它?
我: 封装是一种隐藏客户端信息的机制.该信息可以是数据或实现或算法.我们使用访问修饰符来实现这一点.
采访者:这是数据隐藏.我们如何在Java中实现封装?
我:uummmm
具体问题:除了'Access Modifiers'之外,在Java中实现Encapsulation的方法是什么?
我对这个PropertyUtils.getProperty(bean, fieldName)
方法有一个奇怪的问题,我得到了一个java.lang.NoShuchMethodException
.
假设我们有一个名为pojo的简单java类:
public class Pojo {
public java.util.Date aDate;
public java.util.Date theDate;
public Pojo(){}
}
Run Code Online (Sandbox Code Playgroud)
和一个来电类一样
public class TestPojo{
public static void main(String[] args){
Pojo p = new Pojo();
p.setADate(new Date());
p.setTheDate(new Date());
PropertyUtils.getProperty(p, "theDate");
PropertyUtils.getProperty(p, "aDate");
}
}
Run Code Online (Sandbox Code Playgroud)
第一次PropertyUtils.getProperty
调用工作正常,而第二个会throw
的NoSuchMethodExeption
.
我想知道我是否遗漏了一些愚蠢的东西,或者它真的是一个bug :)
我对如何在Java中使用构造函数和setter感到困惑,请参阅下面的示例代码:
public class Name {
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
public static void main(String[] args) {
Name a=new Name();
a.setName("123");
System.out.println(a.getName());
}
Run Code Online (Sandbox Code Playgroud)
它打印出123,它使用没有构造函数的setter方法,我还编写了下面的其他代码:
public class Name {
private String name;
public Name(String nm){
name=nm;
}
public String getName(){
return name;
}
}
public static void main(String[] args) {
Name a=new Name("123");
System.out.println(a.getName());
}
Run Code Online (Sandbox Code Playgroud)
这个也打印出123,它是使用没有setter方法的构造函数,这就是为什么我不明白构造函数和setter之间使用的区别,请指教,欢呼!
我有2节课
class A {
private int count;
}
class B extends A {
//need to access count here
}
Run Code Online (Sandbox Code Playgroud)
我可以使用哪些标准方法来访问它?
我仍然是Java的新手.我的问题可能非常基本.
我有一个班级超级班,
package chapter8;
public class Box {
double width;
private double height;
private double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
Run Code Online (Sandbox Code Playgroud)
BoxWeight是Box超类的子类:
package chapter8;
public class BoxWeight extends Box {
double weight;
BoxWeight(double w, double h, double d, double m){
super(w, h, d);
weight = m;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我主要在DemoBoxWeight
package chapter8;
public class DemoBoxWeight {
public static …
Run Code Online (Sandbox Code Playgroud)