Can object method call be done simultaneously with object instantiation? - java

I'm trying to use java class BitSet as a field for a customized class. And I want the class to use a default BitSet with all bits set.
import java.util.BitSet;
public class MyClass {
private BitSet mask;
public MyClass() {
this(new BitSet(4));
// want to set all bits first
// something like
// this( new BitSet(4).set(0,3) );
}
public MyClass(BitSet mask) {
this.mask = mask;
}
}
By default BitSet constructor unsets all bits. So before I send it as an anonymous object, I would like call set(int, int) method to set all bits. I know that I could simply initialize the field mask to a new BitSet and then call set(int, int) method from there.
However, in general I'm wondering is it possible to access an instance method at time of object instantiation?

Why not writing a separate constructor that allows for the BitSet initialization? Using Java 8, this could look like something like this:
public class MyClass {
private BitSet mask;
public MyClass() {
this(new BitSet(4),(m)->m.set(0,3));
}
public MyClass(BitSet mask,Consumer<BitSet> initializer) {
initializer.accept(mask);
this.mask = mask;
}
}
You can even make that more generic by introducing a static method with type parameters:
public static <T> T initialize(T t,Consumer<T> initializer) {
initializer.accept(t);
return t;
}
In that case, the earlier MyClass would look as follows:
public class MyClass {
private BitSet mask;
public MyClass() {
this(initialize(new BitSet(4),(m)->m.set(0,3)));
}
public MyClass(BitSet mask) {
this.mask = mask;
}
}
UPDATE
And there is one more way, without introducing new methods or constructors:
public class MyClass {
private BitSet mask;
public MyClass() {
this(new BitSet(4) {{ set(0,3); }});
}
public MyClass(BitSet mask) {
this.mask = mask;
}
}
An anonymous class is being instantiated by extending BitSet and adding an instance initialization block, hence the double curly braces.

BitSet does not have a fluent interface, so something like new BitSet(4).set(0,3) doesn't work for BitSets. There are only the static BitSet.valueOf() methods, but those are somewhat awkward to use. However, if you want a static configuration you could just instantiate a BitSet with the desired value, use BitSet.toLongArray(), print the array values and instantiate your BitSet with it. In your specific example the default constructor could be:
public MyClass() {
this(BitSet.valueOf(new long[]{7}));
}
As for the general part of the question: It would only work if you have a "setter" that returns the current object, that would allow you to chain the calls. So for your own classes you could do something like this:
public class A {
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public A withNum(int num) {
setNum(num);
return this;
}
}
If you used that in a constructor like with the BitSet you can do this(new A().withNum(4));
Fluent interfaces are pretty popular (e.g. the AWS SDK has that everywhere), just the JDK objects don't have them usually.

No; that would have to be done as a separate call, which will be executed after the object's construction has finished. The only way to do it in one line in your situation is if the method's return type had been BitSet and the method had returned the instance it was invoked on, in which case you could have done
this(new BitSet(4).set(0, 1)); // Doesn't actually work
Unfortunately, set() is void, so you can't do this.

Related

Java Access Modifier Best Practice

This may seem a basic question, but I'd like to get this right.
I have a Class 'AWorld'. Within that class, I have a method that draws a border, depending on the map size set by the user.
If the variable 'mapSize' is private, but I want to access it's value from within the same class, is it more appropriate to reference it directly, or use a getter method.
The code below should explain what I'm wanting to know.
package javaFX;
public class AWorld {
//initialized later
AWorld newWorld;
private int mapSize = 20;
public int getMapSize()
{
return mapSize;
}
public void someMethod()
{
int var = newWorld.mapSize; //Do I reference 'mapSize' using this...
}
// Or...
public void someOtherMethod()
{
int var = newWorld.getMapSize(); //Or this?
}
public static void main(String[] args) {}
}
Either of those is ok since you're getting a primitive field. If the get method does another operation before returning the data e.g. performing a math operation on the value, then it would be better to use it rather than calling the field directly. This is specially meant when using proxy/decorator pattern on your classes.
Here's an example of the second statement from above:
//base class to be decorated
abstract class Foo {
private int x;
protected Foo foo;
public int getX() { return this.x; }
public void setX(int x) { this.x = x; }
public Foo getFoo() { return this.foo; }
//method to prove the difference between using getter and simple value
public final void printInternalX() {
if (foo != null) {
System.out.println(foo.x);
System.out.println(foo.getX());
}
}
}
//specific class implementation to be decorated
class Bar extends Foo {
#Override
public int getX() {
return super.getX() * 10;
}
}
//decorator
class Baz extends Foo {
public Baz(Foo foo) {
this.foo = foo;
}
}
public class Main {
public static void main(String[] args) {
Foo foo1 = new Bar();
foo1.setX(10);
Foo foo2 = new Bar(foo1);
//here you see the difference
foo2.printInternalX();
}
}
Output:
10
100
You better dereference it directly.
The point of the private modifier is not to expose internal implementation to other classes. These other classes will use the getter method to get the value of the private property.
In your own class, there is no point on using the getter. Worse, someone may have overridden that method in a class that extends your class, and the getter may perform something that you do not expect
IMHO, if you are referencing a field of the current instance the general rule is to access the field directly with mapSize or this.mapSize.
If you are referencing a value from a different instance (be it of the same class or a different class, I would use the getter method). I believe this would lead to simpler refactoring. It also maintains the contract that any other instance gets the field value via the getter which allows for additional functionality in the getter.

A java method with both variable return type and variable input arguments

I have an abstract java class "BaseOperation". This class only has a single abstract method:
public abstract T execute()
{
...
return T;
}
Subclasses of BaseOperation must implement this method:
public class GetUsersOperation extends BaseOperation<GetUsersResponse>
{
...
#Override
public GetUsersResponse execute()
{
...
return GetUsersResponse;
}
}
This is a great way to put all common "operation" logic in the BaseOperation class, but still have every concrete subclass's execute() method have a different return type.
Now I need to change this structure to allow the execute() methods to have a variable amount of arguments. For example, one concrete subclass would require:
execute(String, int)
and another would need:
execute(Date, Date, String)
This is tricky, because the execute method is declared in the base class. Simply overloading the execute methods in the base is not ideal. Firstly, the amount of overloads would be huge. Secondly, every subclass will only ever use one of the execute methods, what's the point of all the others?
The (in my opinion) easiest solution would be to declare the execute method with varargs:
execute(Object... arguments)
And then downcast all arguments in the subclasses:
execute(Object... arguments)
{
String s = (String) arguments[0];
...
}
Obviously this has 2 major downsides:
Reduced performance because of all the downcasting operations
Calling the execute() methods is no longer strictly typed because any amount of objects can be passed witout compiler warnings.
Are there patterns or other solutions that could don't have these disadvantages?
You could use a bean holding the parameters:
public interface BaseOperation<T, U> {
T execute(U input);
}
public class GetUsersOperation implements BaseOperation<GetUsersResponse, UserInput> {
#Override
public GetUsersResponse execute(UserInput input) {
Date date = input.getDate();
return new GetUsersResponse(date);
}
}
Your abstract class only has one single abstract method: better use an interface. You can implement several interfaces while you can extend only one class.
As already said, the common approach for solving your issue is using a bean holding parameters. But here is another solution, based on a builder approach:
public interface BaseOperation<T> {
public T execute();
}
public class AddOperation implements BaseOperation<Integer> {
private int a, b;
public void setA(int arg){
a = arg ;
return this;
}
public void setB(int arg){
b = arg;
return this;
}
#Override
public Integer execute() {
return a+b ;
}
}
And then use it like this :
new AddOperation().setA(1).setB(2).execute();
You can mix required and optional parameters in this way:
public class MultipleAddOperation implements BaseOperation<Integer> {
private int sum ;
public MultipleAddOperation(int requiredInt){
sum = requiredInt;
}
public void add(int optionalInt){
sum += optionalInt ;
return this;
}
#Override
public Integer execute(){
return sum;
}
}
And so:
new MultipleAddOperation(5).add(1).add(2).execute();

Let a constructor access a static variable

Right now I have two .java files.
The Main.java:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger();
}
and the NeedInteger.java
public class NeedInteger {
System.out.println(integer);
}
This is of course very simplified, but is there any way I can accomplish this?
As many have answered, the correct method is to pass the value in to the constructor of the new class.
If for some reason you cannot do that, then you can use a public static accessor method in Main to access the value (this would be slightly better than just making the field public).
E.g.
public class Main
{
private static int integer = 15;
public static int getInteger()
{
return integer;
}
}
public class NeedInteger
{
public NeedInteger()
{
int integer = Main.getInteger();
}
}
Add a constructor to NeedInteger (and optionally a member if you need to also store it):
public class NeedInteger {
private int integer;
public NeedInteger(int integer) {
this.integer = integer;
System.out.println(integer);
}
}
Then pass your value when you create the instance:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger(integer);
}
You would have to do some bad juju moves (like using a global variable) or pass it to the constructor.
NOTE: your
public class NeedInteger {
System.out.println(integer);
}
has no method in it. I would recommend all this to be rewritten as such:
public Class NeedInteger {
NeedInteger(int integer) {
System.out.println(integer);
}
}
If you really want the work to be done on construction.
EDIT: From your comment above.
Instead, have the class structured so:
public Class NeedStringArray {
NeedStringArray(String[][][] stringArr) {
//work with String array here
}
}
That has no real additional overhead, since the actual array will not be passed, but only a reference to it. You WILL likely want to set the array to be final or something, to avoid it being edited in the NeedStringArray constructors.
integer is private, so it cannot be accessed by NeedInteger. you'll have to make it public or use a setter or getter and you'll need to use Main.integer since it's static.
Generally, you set in the Constructor.
Pass in the variable to the class constructor.
An array reference would be just that--a reference.
Or you could pass in the class itself, or use a static (meh).
Per your comment I'd say you can either host your array in a singleton
or as others suggested have the second class accept the reference to the array in the constructor. You can then use Dependency Injection framework (e.g. Guice) to get wire them up

Reusing class after calling static methods

Suppose I have a class with several static void methods, for example:
class MyClass {
public static void doJob() {
// ...
}
public static void doSmthElse() {
// ...
}
}
how can I modify it to call my static methods like this:
MyClass.doJob().doSmthElse().doJob();
instead of
MyClass.doJob();
MyClass.doSmthElse();
MyClass.doJob();
I know how to do it with non-static methods (just return this), but how to do it with static fields?
Well, you could do this:
// Horrible, don't do it!
class MyClass {
public static MyClass doJob() {
// ...
return null;
}
public static MyClass doSmthElse() {
// ...
return null;
}
}
At that point your code will compile, as Java allows access to static methods "via" references. The fact that you're returning null is irrelevant, because the compiler will only look at the compile-time type of the expression MyClass.doJob() in order to work out which doSmthElse() method to call; the static method will then be called without examining the return value at all.
But please don't do this - it's a really nasty code smell, as your code looks like it's doing one thing when it's actually doing another.
Options:
Just live with your more verbose calls
Extract the static methods into a class where it makes sense for them to be instance methods (this may well improve testability etc as well)
Import the methods statically
Create a larger method in MyClass which calls the three methods one after another.
You can make this class singleton and do
return getInstance();
in every method
You can create a dummy instance of you class and return this. You will use static members of class, but return a reference to regular instance (just for fun, just for code style). But I wouldn't like to use this approach.
class MyClass {
private static int data = 0;
private static MyClass link = null;
public static void doJob() {
// do job with static data such as "data"
return checkMe();
}
public static void doSmthElse() {
// do someting else with static data such as "data"
return checkMe();
}
private MyClass static void checkMe() {
if (link == null) link = new MyClass();
return link;
}
}
It is immpossible because there is no object you can return.

How to create an immutable class in Java without using final keyword [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Implement a final class without the “final” keyword
I want to create an immutable class in Java without using the final keyword.
I think smt like should work fine
class Immutable {
private int i;
public static Immutable create(int i){
return new Immutable(i);
}
private Immutable(int i){this.i = i;}
public int getI(){return i;}
}
But final is preferable.
The final keyword won't make your class inmutable. It will avoid your class to be extended from another class.
public final class Foo {
//....
}
public class Bar extends Foo {
//COMPILATION ERROR!
}
An adecuated class design is what will make you class inmutable, as you can see at duffymo answer.
Note that you can declare as final the fields that you will initialize at the constructor:
class Foo {
private final int state
public Foo(int v) {
this.state=v;
}
//....
}
The difference is that, while at duffymo example, the value ccould be changed from inner routines (i.e, a method adds one to the value, kind of a counter), at my example you wouldn't be able to do so.
Let's try to avoid absolutely the use of the final keyword:
public class Foo {
private int state;
private Foo(int v) {
this.state=v;
}
public static Foo getInstance(int value) {
return new Foo(value);
}
}
You only can get an instance of Foo accesing the Foo.getInstance method.
But anyway, you can extend the Foo class and make it mutable
I was wrong here. I won't compile, as you can acceess the Foo constructor.
public class Bar extends Foo {
private int ohNopes;
//COMPILATION ERROR!
public Bar(int v) {
this.ohNopes=v;
}
}
So, it seems it can be done, after all.
The problem with an immutable class not being final is that, subclasses may not be immutable.
Here is an example from the Java API, java.lang.String is immutable and final, if a string is passed to one of your methods you can be sure that it will remain in a consistent state.
the following will not compile because String is final:
public class MyString extends java.Lang.String {
public MyString(String original) {
Super(original);
}
#Override
public String toString() {
return String.valueOf(System.currentTimeMillis());
}
On the other hand, java.ma.BigDecimal itself is immutable, but it is not final and allowed to be subclassed. This opens up a range of issues. If a BigDecimal is passes to one of your methods you can't rely on the fact that no one has overridden BigDecimal like you can with String. subclasses of BigDecimal could potentially replace its methods with others which give unpredictable results.
The following will compile because BigDecimal is not immutable:
public class MyBigDecimal extends java.math.BigDecimal {
public MyBigDecimal(double val) {
super(val);
}
private int count = 0;
// override intValue which changes the state of this instance
#Override
public int intValue() {
return count++;
}
// rinse and repeat for the rest of the BigDecimal methods...
}
You cannot rely on he state of BigDecimal instances passed into your code, you should make Defensive copies of non final classes if you need to rely on their immutability.
I can't imagine why you object to using final, but here's a class that will get the job done. I know there are subtleties regarding serialization and reflection, but this can't be changed without special shenanigans:
public class Immutable
{
private int value;
public Immutable(int v)
{
this.value = v;
}
public int getValue() { return this.value; }
}
The class should set all its values in the constructor, and provide no setters (methods that modify class members).
You can create a class then create a .jar and use the jar as resource.

Categories