I'm not looking for the best way to do this, but rather for any way to do what i need while adhering to the DRY principle.
Let's say I have a class Source as follows. Source contains thirty strings.
class Source {
private String sourceAttrOne = "sourceValueOne";
private String sourceAttrTwo = "sourceValueTwo";
...
private String sourceAttrThirty = "sourceValueThirty";
}
This information is to be used to create a new object of class Destination. 25 of Destination's attributes have a name in a similar format (but not the same name). 10 of these are Strings, while 5 are Dates, and 5 are Integers. The last 5 fields, however, are totally different.
class Destination {
private String AttrOne;
...
private Date AttrSixteen;
...
private Integer AttrTwentyOne;
...
// Last 5 fields are different
private SomeOtherClass someOtherName;
private TheBestClass imAlsoSpecial;
// Standard getters and setters
}
For the 25 "normal" attributes, I need to use a helper method to get from the source value to the result. The helper method used depends on the destination type:
destination.setAttrOne(getResultingString(source.getSourceAttrOne()));
destination.setAttrSixteen(getResultingDate(source.getSourceAttrSixteen());
destination.setAttrSeventeen(getResultingDate(source.getSourceAttrSeventeen()/*, custom Date format for AttrSeventeen */));
The remaining 5 attributes need custom (individual) logic.
Any pointers in the right direction would be much appreciated, I don't need a complete solution :)
N.B.: I'm probably totally mistaken, so nevermind me if that's the case.
I also haven't unlocked comments yet, while it would be more likely the best; sorry for the inconvenience.
If the 1st to 15th attributes are String, then supposedly, you can simply affect them to the corresponding attributes, or clone them first, if you prefer.
For the 16th to 21th(?), which are dates, you might be able to use DateFormat's parse(String) method; although, I'm clueless on how to help the compiler to get the used format or if it can do it properly by itself.
For the 22th to 27th(?), the Integers, you should be able to use Integer's parse(String) method, or possibly through Double's and then convert back to an Integer or an int.
You can try Reflection for similar targets.
Something like:
public void fillFieldsHelper(Object source) {
List<Field> sourceFields = source.getClass().getDeclaredFields();
or
Field valueOne = source.getClass().getDeclaredField("sourceAttrOne");
System.out.println(valueOne.getName());
System.out.println(valueOne.getType());
...
Object value = valueOne.get(source);
Field attrOne = this.getClass().getDeclaredField(valueOne.getName().replace("source",""));
switch (attrOne.getType().getName()) {
case "java.lang.Integer":
attrOne.set(this, Integer.valueOf(value));
break;
default:
attrOne.set(this, value);
}
...
etc.
I can't say that Reflection is elegant but it's useful in many cases.
So in your case you have several possibilities.
Create Object from Object
The easiest but maybe not the nicest solution (depending on your further process/requirements) is to have a constructer which has the need Object as parameter.
public class Source {
private String sourceAttrOne;
private String sourceAttrTwo;
// further class attributes....
// getters (& setters)
}
public class Destination {
private String attrOne;
private String attTwo;
public Destination(Source source) {
this.attrOne = source.getSourceAttrOne;
this.attrTwo = source.getSourceAttrTwo;
// etc..
}
}
User Builder Pattern
The problem in the solution above is, that depending of which fields are required for creating the Destination.class the constructer is going to have a lot of parameters. In addition, if you have to change your constructer in the future (e.g. additional required fields), you have to create a new constructer or change the already existing one (which implies you have to change all the current usages of that).
Therefore to hold the DRY, I would recommend the Builder Patter.
public class Destination {
private String attrOne;
private String attTwo;
private String attThree; // attribute which comes not from any other source class and is e.g. not a required field
private Destination() {
// should not be accessible
}
public static class Builder {
private String attrOne;
private String attTwo;
private String attThree;
private Builder() {
// do nothing
}
public static Builder create(Source source) {
Builder builder = new Builder();
builder.attrOne = source.getSourceAttrOne();
builder.attrTwo = source.getSourceAttrTwo();
return builder;
}
public Builder attThree(String attThree) {
this.attThree = attThree;
return this;
}
public Destination build() {
Destination destination = new Destination();
destination.attrOne = builder.attrOne;
destination.attrTwo = builder.attrTwo;
destination.attrThree = builder.attrThree;
//add several validations e.g. assert destination.attrOne != null
return destination;
}
}
}
To create a Destination.class with Source.class you can do following:
Destination.Builder.create(source).build();
For having different Types e.g. Source.sourceAttrOne is a String and the in the Destination.attrOne is a Date, you just have to adjust the Destination.class.
public class Destination {
private LocalDate attrOne;
// ...
private Destination() {}
public static class Builder {
private String attrOne;
// ...
private Builder() {}
public static Builder create(Source source) {
Builder builder = new Builder();
builder.attrOne = LocalDate.parse(source.getSourceAttrOne());
// ...
return builder;
}
public Destination build() {
Destination destination = new Destination();
destination.attrOne = builder.attrOne;
// ...
return destination;
}
}
}
Related
I am writing a RequestBuilder class, which will handle the creation of a query string, based on the following criteria
category (String)
country (String)
keywords (String[])
page (int)
pageSize (int)
Since not all criteria are mandatory and there are many combinations between them (I counted 7, of which only four should be valid - see below why), I decided to use the builder pattern:
public class RequestBuilder {
private String category = "";
private String country = "&country=us";
private String keywords = "";
private String page = "";
private String pageSize = "&pageSize=100";
public RequestBuilder() {
}
private String buildQuery() {
return this.category + this.country + this.keywords + this.page + this.pageSize;
}
// the setter methods, which I omitted for readability
But there is a problem. I need to force the user to specify at least two of either category, country or keywords before building the object(right now the user isn't obliged to specify even one!). A user shouldn't be able to create an object by specifying only country, for example.
So how do I force this requirement? If I make three constructors(each having two of those parameters) I feel like I am ruining the Builder pattern, even though there will be three more optional properties to specify.
As a designer, you need to decide what fields are really required. There is no such thing as "maybe required". To use Builder Pattern and enforce required parameters, mark the fields as final and inject them through the constructor:
public class Request {
// fields
private final String requiredField;
private final String optional1;
private final String optional2;
private Request(RequestBuilder builder) {
requiredField = builder.requiredField;
optional1 = builder.optional1;
optional2 = builder.optional2;
}
// add only getter method to the Request class (builds immutable Request objects)
public static class RequestBuilder {
private final String requiredField;
private String optional1;
private String optional2;
public RequestBuilder(String requiredField) {
this.requiredField = requiredField;
}
public RequestBuilder setOptional1(String optional1) {
this.optional1 = optional1;
return this;
}
public RequestBuilder setOptional2(String optional2) {
this.optional2 = optional2;
return this;
}
public Request build() {
return new Request(this);
}
}
}
The builder enforces required and optional fields. The object being built by the builder hides the constructor so that it is only accessible via the builder. The fields inside the request object are all final for immutability.
To use, you'll do something like this:
RequestBuilder builder = new RequestBuilder("required");
Request request = builder.setOptional1("foo").setOptional2("bar").build();
or you could simply call build() at any time after calling the builder constructor.
UPDATE:
Now to your problem.... You could (potentially) modify the build() to check how many "semi-required" fields you have with values and compare it to the total number of fields. To me, this is a hack. For this, you have two options
Hard code the number of fields and check how many out of the total number are still null or empty. If the number of fields that are not set is below a certain count, throw some exception (i.e. InvalidRequiredFieldCount). Otherwise, you return the new instance. For this, you need to increment the "count" every time a setter method is called.
Use reflection to get the list (array) of fields and use this field and use this field count to calculate the minimum number of "required" fields. Throw exception if that minimum is not reach or return a new request instance if the minimum threshold is reached.
public Request build() throws Exception {
Request request = new Request(this);
int count = 0;
int max = 2;
Field[] allFields = Request.class.getDeclaredFields();
for (Field field : allFields) {
Object o = field.get(request);
if (o != null) {
count++;
}
}
if (count < 2) {
throw new Exception("Minimum number of set fields (2) not reached");
}
return request;
}
This is not pretty, but it works. If I run this:
RequestBuilder builder = new RequestBuilder("required");
Request request = builder.build();
will result in an exception:
Exception in thread "main" java.lang.Exception: Minimum number of set fields (2) not reached
at com.master.oxy.Request$RequestBuilder.build(Request.java:54)
at com.master.oxy.Request.main(Request.java:63)
However, if I set at least one optional, the new instance will be returned.
I would like to suggest another object-oriented solution for that problem:
Let's assume you don't want to pass the required arguments to the builder c'tor. You can use the following technique to enforce providing the required field during the build process of the object:
Usage - demonstrate how only the required field is visible first:
Usage2 - demonstrate how the rest of the optional and build() methods are visible after providing the required field:
We implement it by doing the following:
public static class RequestBuilder implements RequestBuilderRequiredField {
public interface RequestBuilderRequiredField {
RequestBuilder setRequiredField(String requiredField)
}
private final String requiredField;
private String optional1;
private String optional2;
private RequestBuilder() {
}
public static RequestBuilderRequiredField aRequestBuilder() {
return new RequestBuilder();
}
Note the the builder c'tor is private because we want to expose first the interface with the required field (and if have many, we want to chain the interfaces methods so they will return an interface for for each required field)
The downside of that approach is that you need to maintain the same amount of interfaces on a large object when many (or even all) properties are required.
Interesting to think if libraries such as Lombok that auto generates Builder with #Builde annotation can have the ability to generate it
While creating JUnit test cases, it takes a long time to reconstruct objects for every single one of them and perform some operations that all my unit tests use.
Is there anyway I can make some objects in a test case that I can freely use in all of my tests without recreating them each time?
Thanks in advance!
A simple way of doing this is to create a private method that creates test objects. These can take in the parameters (the ones that need to change in the various test cases), or just provide a default object that you could in turn change. If the same objects are used in multiple tests, then a testdata-builder might be what you are looking for.
Say you have a class like this:
public class Something {
private String someString;
private Integer someInt;
public Something(final String someString, final Integer someInt) {
this.someString = someString;
this.someInt = someInt;
}
//getters and stuff
}
Then you can create a testdata builder like this:
public class SomethingBuilder {
private String someString;
private Integer someInt;
public SomethingBuilder() {
someString = "Some default value";
someInt = 42;
}
public SomethingBuilder withSomeString(final String someString) {
this.someString = someString;
return this;
}
public SomethingBuilder withSomeInt(final Integer someInt) {
this.someInt = someInt;
return this;
}
public Something build() {
final Something something = new Something(someString, someInt);
return something;
}
}
Then, creating test data becomes really simple, you can mutate the fields you different than your default values easily:
final Something something =
new SomethingBuilder().withSomeString("I want to override the default!").build();
Might seem like a bit of overkill for my small, example class, but if you have a central data class that appears in many tests, it will save you a lot of time and lines of code.
I'm just starting my first steps with Java, learned all the basics but then found a problem with an enum I need, so forgive me, if the solution to my problem is something very obvious:
So I've got this enum and want to add a unique id to each instance counting from 0 upwards, but without having to add another parameter to each constructor calling (because this can later on lead to errors ofc).
public enum TerrainTile{
WATER(1), GRASSLAND(1), HILL(2), FORREST(2), BLANK(99);
private final int id;
private final int moveCost;
private boolean hidden = true;
private TerrainTile(int moveCost) {
this.moveCost = moveCost;
}
And I thought to just add a
static int nextID = 0;
and edit the constructor to
private TerrainTile(int moveCost) {
this.id = nextID++;
this.moveCost = moveCost;
}
But I get an error message that it can not refer to a static field inside the initializer.
Is there any workaround?
You can use the ordinal() method for it. It is based on the order in which the members are declared in the source-code and counted from zero. So I guess, exactly what you need.
Just a note:
You can get your original enum member from ordinal number by calling .values()[index]
example:
int hillOrdinal = TerrainTile.HILL.ordinal(); // 2
TerrainTile hill = TerrainTile.values()[hillOrdinal];
It sounds like you are trying to combine class features into an enum. I'd be particularly wary of non-final, non-static member fields in an enum declaration. The behaviour you want seems to be best served by using a TerrainTile class (possibly a flyweight if you truly want the single-instance-per-type behaviour) and a TerrainTileType (or TerrainTile.Type) enum. Something like this:
public class TerrainTile {
public enum Type {
WATER(1), GRASSLAND(1), HILL(2), FORREST(2), BLANK(-1);
public final int MOVE_COST;
private TerrainTile(int moveCost) {
this.MOVE_COST = moveCost;
}
public boolean isTraversable() {
return (MOVE_COST > 0);
}
}
private final Type type;
private final Image texture;
...
private TerrainTile(Type type) {
this.type = type;
}
private static final Map<Type, TerrainTile> tiles = new EnumMap<>();
static {
// instantiate one TerrainTile for each type and store into the tiles Map
for (Type type: Type.values()) {
// Eventually, also load tile textures or set Color in this step
tiles.put(type, new TerrainTile(type));
}
}
public static TerrainTile getTile(Type type) {
// return the reference to the TerrainTile of this type
return tiles.get(type);
}
...
}
Let's say I have an abstract class (BaseThing). It has one required parameter ("base required") and one optional parameter ("base optional"). I have a concrete class that extends it (Thing). It also has one required parameter ("required") and one optional parameter ("optional"). So something like:
public abstract class BaseThing {
public static final String DEFAULT_BASE_OPTIONAL = "Default Base Optional";
private final String baseRequired;
private String baseOptional = DEFAULT_BASE_OPTIONAL;
protected BaseThing(final String theBaseRequired) {
this.baseRequired = theBaseRequired;
}
final void setBaseOptional(final String newVal) {
this.baseOptional = newVal;
}
public final void selfDescribe() {
System.out.println("Base Required: " + baseRequired);
System.out.println("Base Optional: " + baseOptional);
selfDescribeHook();
}
protected abstract void selfDescribeHook();
}
and:
public final class Thing extends BaseThing {
public static final String DEFAULT_OPTIONAL = "Default Optional";
private final String required;
private String optional = DEFAULT_OPTIONAL;
Thing(final String theRequired, final String theBaseRequired) {
super(theBaseRequired);
required = theRequired;
}
#Override
protected void selfDescribeHook() {
System.out.println("Required: " + required);
System.out.println("Optional: " + optional);
}
void setOptional(final String newVal) {
optional = newVal;
}
}
I want to have a Joshua Bloch-style builder for Thing objects. More generally, though, I want to make it easy for concrete implementations of BaseThing to have builders, so what I really want (I think) is a BaseThing builder that can easily be used to make a ThingBuilder, or an OtherThingBuilder, or a SuperThingBuilder.
Is there a better way than the following that I've come up with (or are there problems with what I've come up with)?
public abstract class BaseThingBuilder<T extends BaseThing> {
private String baseOptional = BaseThing.DEFAULT_BASE_OPTIONAL;
public BaseThingBuilder<T> setBaseOptional(final String value) {
baseOptional = value;
return this;
}
public T build() {
T t = buildHook();
t.setBaseOptional(baseOptional);
return t;
}
protected abstract T buildHook();
}
and:
public final class ThingBuilder extends BaseThingBuilder<Thing> {
private final String baseRequired;
private final String required;
private String optional = Thing.DEFAULT_OPTIONAL;
public ThingBuilder(final String theRequired,
final String theBaseRequired) {
required = theRequired;
baseRequired = theBaseRequired;
}
public ThingBuilder setOptional(final String value) {
optional = value;
return this;
}
protected Thing buildHook() {
Thing thing = new Thing(required, baseRequired);
thing.setOptional(optional);
return thing;
}
}
Which can be used to build Thing objects in a manner similarly to the following:
BaseThingBuilder<Thing> builder =
new ThingBuilder("Required!", "Base Required!")
.setOptional("Optional!")
.setBaseOptional("Base Optional!");
Thing thing = builder.build();
thing.selfDescribe();
Which outputs:
Base Required: Base Required!
Base Optional: Base Optional!
Required: Required!
Optional: Optional!
One issue that I know about, but that I don't consider particularly important (though if it can be improved it would be nice to do so) is that you have to set all non-base options before you set any base option: Doing otherwise would result in a syntax error, as setBaseOptional() returns a BaseThingBuilder rather than a ThingBuilder.
Thanks in advance.
I don't think it's a good idea to think of builders that way. A hierarchy of builders usually leads to headaches and fragile code.
Cutting down the amount of code that needs to be written in the concrete builders and reusing logic from the base builder is closely tied to the domain. It's not easy to develop a general solution. But, let's try to go through an example anyway:
public interface Builder<T> {
T build();
}
public class Person {
private final String name;
//the proper way to use a builder is to pass an instance of one to
//the class that is created using it...
Person(PersonBuilder builder) {
this.name = builder.name;
}
public String getName(){ return name; }
public static class PersonBuilder implements Builder<Person> {
private String name;
public PersonBuilder name(String name){ this.name = name; return this; }
public Person build() {
if(name == null) {
throw new IllegalArgumentException("Name must be specified");
}
return new Person(this);
}
}
}
Groovy, baby! Now what? Maybe you want to add a class to represent a student. What do you do? Do you extend Person? Sure, that's valid. How about taking a more "strange" route and attempting aggregation? Yep, you can do that too... Your choice would have an affect on how you will end up implementing builders. Let's say you stick to the traditional path and extend Person (you should already starting asking yourself, does it make sense for Person to be a concrete class? If I make it abstract, do I really need a builder? If the class is abstract should the builder be abstract?):
public class Student extends Person {
private final long id;
Student(StudentBulder builder) {
super(builder);
this.id = builder.id;
}
public long getId(){ return id; }
//no need for generics, this will work:
public static class StudentBuilder extends PersonBuilder {
private long id;
public StudentBuilder id(long id){ this.id = id; return this; }
public Student build() {
if(id <= 0) {
throw new IllegalArgumentException("ID must be specified");
}
return new Student(this);
}
}
}
Ok, this looks exactly like what you wanted! So, you try it:
Person p = new PersonBuilder().name("John Doe").build();
Student s = new StudentBuilder().name("Jane Doe").id(165).build();
Looks great! Except, it doesn't compile... There's an error at line 2 and it states The method id(int) is undefined for the type Person.PersonBuilder. The problem is that PersonBuilder#name returns a builder of type PersonBuilder, which isn't what you want. In StudentBuilder you actually want the return type of name to be StudentBuilder. Now, you think ahead and realize that if anything extends StudentBuilder you'd want it to return something else entirely... Is that doable? Yes, with generics. However, it's ugly as hell and introduces quite a bit of complexity. Therefore, I refuse to post the code that illustrates it, for the fear that someone will see this thread and actually use it in their software.
You might think rearranging method calls will work (calling id before calling name): new StudentBuilder().id(165).name("Jane Doe").build(), but it won't. At least not without an explicit cast to Student: (Student)new StudentBuilder().id(165).name("Jane Doe").build() since, in this case, PersonBuilder#build is being called which has a return type of Person... This is simply unacceptable! Even if it worked without an explicit cast, it should make you wince to know that a builder's methods must be called in a certain order. Because if you don't, something won't work...
There are many more problems that would arise if you continue trying to get it to work. And even if you did get it to work, I don't think it would be easily comprehensible and certainly not elegant. Of course, feel free to prove me wrong and post your solution here.
By the way, you should also ask yourself what is an abstract builder? Because, it sounds like an oxymoron.
In the end, I believe that the scope of this question is too great. The answer is domain-specific and hard to come up with in the absence of your requirements. Just remember, the general guideline for builders is to have them be as simple as possible.
Also, take a look at a related question.
As far as I can tell if you remove the generics then
BaseThingBuilder<Thing> builder =
new ThingBuilder("Required!", "Base Required!")
changes to
BaseThingBuilder builder =
new ThingBuilder("Required!", "Base Required!")
The rest of it all remains same, including the restriction that subclass has to be initialized first. So I really don't think this warrants use of generics. Maybe I am missing something.
I seem to remember something like this from Bjarne Stroustrup, long back...
I have a public class, which needs 7 parameters to be passed down. At the moment, I am able to make 3 of them being passed to constructor and another 4 to a public method in the class . Like this:
Public Class AClass{
private XClass axClass;
private String par4;
private String par5;
private String par6;
private String par7;
public AClass(String par1, String par2, String par3){
aXClass = new XClass(par1,par2,par3);
}
public execute(String par4,String par5, String par6, String par7){
//this is needed because they are used in other private methods in this class
this.par4 = par4;
this.par5 = par5;
this.par6 = par6;
this.par7 = par7;
//call other private methods within this class.
//about 7 lines here
}
}
My question is, is this the right way to ask client of the class to passing in paramters?
There shouldn't be anything stopping you from passing 7 parameters to a constructor, if that's what you want. I don't know if there's a maximum number of parameters that can be passed to a method in Java, but it's certainly higher than 7 if there is a max.
When you create a class and its public methods, you're creating an interface on how to use and access that class. So technically what you've done so far is correct. Is it the "right way" to ask the client of a class to pass in arguments? That's up to you, the designer of the interface.
My first instinct when I saw 7 parameters being passed was to silently ask "Is there some relationship between some or all of these parameters that might mean they'd go together well in a class of their own?" That might be something you address as you look at your code. But that's a question of design, not one of correctness.
I'd go for the Builder Pattern instead of many constructor parameters as suggested by
Effective Java Item 2: Consider a builder when faced with many constructor parameters
Here's a simple class to illustrate:
public class Dummy {
private final String foo;
private final String bar;
private final boolean baz;
private final int phleem;
protected Dummy(final Builder builder) {
this.foo = builder.foo;
this.bar = builder.bar;
this.baz = builder.baz;
this.phleem = builder.phleem;
}
public String getBar() {
return this.bar;
}
public String getFoo() {
return this.foo;
}
public int getPhleem() {
return this.phleem;
}
public boolean isBaz() {
return this.baz;
}
public static class Builder {
private String foo;
private String bar;
private boolean baz;
private int phleem;
public Dummy build() {
return new Dummy(this);
}
public Builder withBar(final String bar) {
this.bar = bar;
return this;
}
public Builder withBaz(final boolean baz) {
this.baz = baz;
return this;
}
public Builder withFoo(final String foo) {
this.foo = foo;
return this;
}
public Builder withPhleem(final int phleem) {
this.phleem = phleem;
return this;
}
}
}
You would instantiate it like this:
Dummy dummy = new Dummy.Builder()
.withFoo("abc")
.withBar("def")
.withBaz(true)
.withPhleem(123)
.build();
The nice part: you get all the benefits of constructor parameters (e.g. immutability if you want it), but you get readable code too.
Can't you just make a class/hashmap that stores these parameters and pass this to the function?
public excute(Storageclass storageClass){
//this is needed because they are used in other private methods in this class
this.par4 = storageClass.getPar4();
this.par5 = storageClass.getPar5();
this.par6 = storageClass.getPar6();
this.par7 = storageClass.getPar7();
//or
this.storageClass = storageClass;
}
I don't really see the problem with that.
In any case you could create a "Request" object or something like this:
class SomeClass {
private String a;
private String b;
....
public SomeClass( Request r ) {
this.a = r.get("a");
this.b = r.get("b");
...
}
public void execute( Request other ) {
this.d = other.get("d");
this.e = other.get("d");
...
}
}
See also: http://c2.com/cgi/wiki?TooManyParameters
Without knowing the use of the child class, I can say that there is nothing inherently wrong with what you have done.
Note though that you have to declare
private XClass axClass;
in the variables of your AClass.
However, you say 'I am able to make....' Does this mean there is some problem with declaring this another way?
I don't care for it much, because an object should be 100% ready to be used after its constructor is called. It's not as written in your example.
If the parameters passed into the execute method can simply be consumed, and that's the method of interest for clients, I see no reason for them to be data members in the class.
Without knowing more about your ultimate aims it's hard to tell. But I would re-think this implementation.
If you're planning on introducing an AClass.someMethod() that needs to know par4-7 without requiring you to have called AClass.excute(), then clearly you should be passing the parameters in the constructor.
On the other hand: if you can construct an instance of this object with only par1-3 and do something meaningful with it besides call excute() then it makes sense to allow the object to be constructed with fewer than the full seven parameters.
Yet my own aesthetic is to try and limit the number of "modes" that an object can be in which make certain methods work and others fail. So ideally, a fully-constructed object is ready to run any method the programmer might call. I'd worry about the design issue more than be too concerned about the sheer number of parameters to the constructor.
But as others have pointed out, sometimes there is a natural grouping of these parameters which can deserve objects of their own. For instance: in many APIs instead of passing (x, y, width, height) all over the place they use rectangle objects.
As others already wrote, it is technically correct to pass 7 parameters, although not very 'user-friendly', if you can say so.
Since you didn't write much about this class, I can suggest one small thing: in constructor you're just creating XClass object, so it would be sane to create this object before and pass it as a single parameter.
Something like this:
...
XClass aXClass = new XClass(par1, par2, par3);
AClass aClass = new AClass(aXClass);
...
And this is the constructor:
public AClass(XClass aXClass) {
this.aXClass = aXClass;
}