I would like to implement a strong encapsulated version of object composition using Java. My current code in PHP is the follow:
<?php
class Email {
private $subject;
private $body;
private $recipient;
public function __construct() {
$this->subject = new class {
public $text;
};
$this->body = new class {
public $text;
public $format;
};
$this->recipient = new class {
public $address;
};
}
public function setSubject($text){
$this->subject->text = $text;
}
//more getters & setters...
}
I have tried this in Java, but without success:
public class Email {
private Subject subject;
private Body body;
private Recipient recipient;
public Email() {
this.subject = new Object() {
public String text;
};
this.body = new Object() {
public String text;
public String format;
};
this.recipient = new Object() {
public String address;
};
}
public void setText(String text){
this.body.text = text;
}
//more getters & setters...
}
JDK error saying that Object class does not contain "text" property. So, is it possible to use anonymous classes in Java like in PHP (without classes names?)
Thanks in advance.
So I'm no PHP developer -- I did PHP 5 once and that was enough -- so I'm not 100% on all the aspects of what PHP supports in this case.
However, I think what you want are private inner classes. A public class can have private inner classes that only it has access to. So, for your Email example ...
public class Email {
private Subject subject;
private Body body;
private Recipient recipient;
public Email() {
this.subject = new Subject();
this.body = new Body();
this.recipient = new Recipient();
}
public void setText(String text){
this.body.text = text;
}
//more getters & setters...
private class Subject {
public String text;
}
private class Body {
public String text;
public String format;
}
private class Recipient {
public String address;
}
}
Since Subject, Body, Recipient are private inner classes, external classes can't see them. So you can't return an instance of, say, Body and expect some external class to be able to do work on it because the external class can't even see its definition to import it. But if your getters and setters fully encompass all read/write operators that should be fine for your use case.