How to write a java program making use of static variables such that only an even number of objects of a certain class X can be instantiate.
E.g. Only allowed to create 2 or 4 or 6....(etc.) objects of that class but never 1 or 3 or 5 (etc.)
I am going to write this an "instance" version of the question as global state should be avoided.
package thing; // Use packages.
public class Thing {
// Hide this constructor.
/* pp */ Thing() {
}
}
package thing;
// We need this because single return value.
// Alternatively, you could have a pair of Consumers
// or a BiConsumer (which apparently is a thing,
// notably Map.forEach and Collector.accumulator).
public interface ThingPair {
Thing a();
Thing b();
}
package thing;
public class Things {
// Return a pair of things at once.
public ThingPair makePair() {
Thing a = new Thing();
Thing b = new Thing();
return new ThingPair() {
public Thing a() { return a; }
public Thing b() { return b; }
}
}
}
Related
Okay, so I'm not sure if this question already exists because I don't know how to format it, but here's the problem: can a same method produce different result depending on a constructor? (I apologize if I'm repeating the question or if it's a stupid question.)
For example, let's say that I have an interface MyInterface with function public void foo();. Let's say we have class:
public class MyClass implements MyInterface {
public MyClass() {
// I want foo() to print "Empty constructor" with sysout.
}
public MyClass(int x) {
// I want foo() to print "Constructor with int" with sysout.
}
}
So now, if create two references MyClass mc1 = new MyClass(); and MyClass mc2 = new MyClass(5); and then call mc1.foo(); and mc2.foo();, the result should be:
Empty constructor.
Constructor with int.
I tried with new MyInterface { #Override public void foo() { ... } } inside constructors but doesn't seem to work.
Yes. Store the variable and check it in the foo method.
public class MyClass implements MyInterface {
private int x;
public MyClass() {
// I want foo() to print "Empty constructor" with sysout.
}
public MyClass(int x) {
// I want foo() to print "Constructor with int" with sysout.
this.x = x;
}
public void foo(){
if(x > 0)
System.out.println("Constructor with int");
else
System.out.println("Empty constructor");
}
}
To answer the question: Not to my knowledge. Or at least not directly, you could start to read byte code and change it during run time, make it adapt-- so again, the answer is no.
Now the weird parts are the override and depending on constructor. It is not in the scope of overriding.
A method doing different things depending on the state of the Class is not too odd. However, making the method unique of how the class was instantiated I've never heard of. That being said, here is a fairly ugly solution to it.
public class Test
{
private final boolean intConstructorUsed;
public Test () {
intConstructorUsed = false;
}
public Test (int x) {
intConstructorUsed = true;
}
public void foo () {
if (intConstructorUsed == true) {
// do this
} else {
// do that
}
}
}
The foo method isn't that weird. The weird part is that you basically have to different implementations of foo depending on which constructor, you are sure you do not want an abstract class behind, with all shared methods except for one abstract void foo () that you override? Sure the classes will almost look identical, however they are not, as they do not share their foo ().
Yes, it's what's multiple constructors are designed to allow for - variation via object creation.
public class MyClass implements MyInterface {
private final String message;
public MyClass() {
message = "Empty constructor";
}
public MyClass(int x) {
message = "Constructor with int";
}
#Override
public void foo() {
System.out.println(message);
}
}
It's even threadsafe.
The thing to note here is that the implementation of the method is exactly the same, the variation is in the constructor. And it's the constructor which is called differently depending on what the caller wants to happen.
It seems that Java 8 allows full fledged inheritance with a simple framework as below, using Static and Default methods on interfaces.
While its always possible to misuse and write stupid code, these new features make it quite easy to achieve multiple inheritance, even if the designers of the language meant to stay away from it.
Is this a simple implementation of Multiple Inheritance using Interfaces as base classes, or a misuse of the language?
Did Java designers go too far in allowing this?
package PseudoMultipleInheritance;
import java.util.HashMap;
abstract class InstanceMap<T,T2>
{
HashMap<Object,Object> instances = new HashMap<Object, Object>();
abstract T2 createMembersInstance();
T2 getMembersInstance(T thisObject )
{
if ( !instances.containsKey(thisObject) )
instances.put(thisObject,createMembersInstance());
return (T2) instances.get(thisObject);
}
}
interface A
{
class Members
{
int x; // just an example of an inheritable member
}
InstanceMap<A,A.Members> instanceMap = new InstanceMap<A, A.Members>() { A.Members createMembersInstance() {return new A.Members(); }};
default A.Members thisA() { return instanceMap.getMembersInstance(this); }
default int getX()
{
return thisA().x; // // just an example of an inheritable getter
}
default void setX(int x)
{
thisA().x = x; // just an example of an inheritable setter
}
}
interface B
{
class Members
{
int y; // just an example of an inheritable member
}
InstanceMap<B,B.Members> instanceMap = new InstanceMap<B, B.Members>() { B.Members createMembersInstance() {return new B.Members();} };
default B.Members thisB() { return instanceMap.getMembersInstance(this); }
default int getYLastDigit()
{
return thisB().y % 10; // just an example of an inheritable function
}
default void incrementY(int x)
{
thisB().y += x; // just an example of an inheritable function
}
}
class C implements A, B
{
}
public class Example04AlmostMultipleInheritance {
public static void main(String[] args) {
C c1 = new C();
C c2 = new C();
c1.setX(5);
c2.setX(3);
System.out.println(c1.getX()); // prints 5
System.out.println(c2.getX()); // prints 3
c1.incrementY(99);
System.out.println(c1.getYLastDigit()); // prints 9
}
}
///////////////////////////////////////////////////
Or for yet another option:
interface A
{
class Members
{
public int x; // just an example of an inheritable member
void showX() { System.out.println(x); } // just an example of an inheritable function
}
InstanceMap<A,A.Members> instanceMap = new InstanceMap<A, A.Members>() { A.Members createMembersInstance() {return new A.Members(); }};
default A.Members getA() { return instanceMap.getMembersInstance(this); }
}
interface B
{
class Members
{
int y; // just an example of an inheritable member
}
InstanceMap<B,B.Members> instanceMap = new InstanceMap<B, B.Members>() { B.Members createMembersInstance() {return new B.Members();} };
default B.Members getB() { return instanceMap.getMembersInstance(this); }
}
class C implements A, B
{
}
public class Example04AlmostMultipleInheritance {
public static void main(String[] args) {
C c1 = new C();
C c2 = new C();
c1.getA().x = 5;
c2.getA().x = 3;
c1.getA().showX(); // prints 5
c2.getA().showX(); // prints 3
c1.getB().y = 99;
System.out.println(c1.getB().y % 10); // prints 9
}
}
Implementing an interface is not inheritance. It's as simple as that.
what if someone implements both your interfaces but supplies a different implementation than the default one?
So no, this is not multiple inheritance, It's simply a way to write your code that depends on nobody actually implementing their own version of the default methods. Which means that it depends on people not actually using interfaces the way they're supposed to, because they are supposed to be able to implement their own methods instead of the defaults, but if they actually do that your "multiple inheritance" does not work as expected.
So I'd actually consider this to be misuse of the language.
It is A form of multiple inheritance, but it's not the "Diamond Problem" that is usually brought up when discussing multiple inheritence. Java's implementation is almost the same as Scala's solution to the same thing, which is somewhat similar to how Python implements multiple inheritance.
no, see example of multiple inheritance here: http://java.dzone.com/articles/interface-default-methods-java
I am have a number of classes which implement same interface. The objects for all those classes have to be instantiated in a main class. I am trying to do it in a manner with which this thing could be done in an elegant manner (I thought through enum). Example code :-
public interface Intr {
//some methods
}
public class C1 implements Intr {
// some implementations
}
public class C2 implements Intr {
// some implementations
}
...
public class Ck implements Intr {
// some implementations
}
public class MainClass {
enum ModulesEnum {
//Some code here to return objects of C1 to Ck
FIRST {return new C1()},
SECOND {return new C2()},
...
KTH {return new Ck()};
}
}
Now in the above example for some elegant way with which I can get instances of new objects of Class C1 to Ck. Or any other better mechanism instead of enum will also be appreciated.
enum ModulesEnum {
FIRST(new C1()), SECOND(new C2()); // and so on
private ModulesEnum(Intr intr) { this.obj = intr; }
private Intr obj;
public Intr getObj() { return obj; }
}
Hope that helps. The trick is to add an implementation to every enum. If you want to access the object, use the getter.
ModulesEnum.FIRST.getObj();
If your Intr and its implementations are package protected, you can make ModulesEnum public to expose the implementations. This way you can have only one instance per implementation, making them singleton without using the pattern explicitly.
You can of course use a Factory too if you intend to have multiple instances for every implementation.
What you need is the Factory pattern. Whether or not you need want to use the Enum class as the factory itself is another issue. You could do something like this:
public enum Module {
FIRST, SECOND, ..., KTH
}
public class ModuleFactory {
public Intr createModule(Module module) {
switch (module) {
case FIRST:
return new C1();
case SECOND:
return new C2();
...
case KTH:
return new Ck();
...
}
}
}
Without knowing how you plan on using these objects, I can't really say which is the more appropriate approach.
Use a static factory.
public IntrFactory {
static Intr first() {
return new C1();
}
static Intr second() {
return new C2();
}
...
}
Executed Python code:
class Test(object):
item = 0
def __init__(self):
print(self.item)
def test(self):
print(self.item)
class Subclass(Test):
item = 1
s = Subclass()
s.test()
gives:
1
1
Executed analogical Java code:
public class Test {
int item = 0;
Test(){
System.out.println(this.item);
}
void test(){
System.out.println(this.item);
}
public static void main(String[] args){
Subclass s = new Subclass();
s.test();
}
}
class Subclass extends Test {
int item = 1;
}
gives:
0
0
Apparently, Java method inherited from base class (Test) uses also base class' member variables. Python method uses the member variable of derived class (Subclass).
The question: Is there any way to achieve the same or at least similar behaviour in Java like in Python?
Objects in Python are pretty much just like Dictionaries in Python. You can think of each instance of Test and Subclass as a Dictionary that is updated by the __init__ code and assignments in the body of the class you declare. You can picture the code you wrote working something like this:
class Test(object):
item = 0 # self['item'] = 0
def __init__(self):
print(self.item) # print(self['item'])
def test(self):
print(self.item) # print(self['item'])
class Subclass(Test):
item = 1 # self['item'] = 1
s = Subclass() # Test.__init__({})
s.test()
Python uses duck-typing, so item is just some property of whatever you happen to have an instance of. Notice that you don't ever actually have to declare item—you just assign a value. This is why you're able to "override" the value in the sub-class—because you're actually just overwriting the old value of the same field. So in the example you gave, the item in Subclass isn't actually overriding the item in Test; rather, they are the same field in a Python object instance.
In Java fields actually belong to specific classes. Notice how in your code you actually have two declarations of the field int item: one in Test and one in Subclass. When you re-declare the int item in Subclass you are actually shadowing the original field. See Java in a Nutshell: 3.4.5. Shadowing Superclass Fields for more info.
I'm not sure exactly what you're trying to do with your example, but this is a more idiomatic Java approach:
public class Test {
private int item;
public Test() {
this(0); // Default to 0
}
public Test(int item) {
setItem(item);
test();
}
public void test() {
System.out.println(getItem());
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.test();
}
public void setItem(int item) {
this.item = item;
}
public int getItem() {
return item;
}
}
class Subclass extends Test {
public Subclass() {
super(1); // Default to 1
}
}
Notice how the value of item is set via a constructor argument rather than by simple assignment. Also notice how item is private and that there is now a getter and setter method to access it. This is more Java-style encapsulation.
That seems like a lot of code, but a good IDE (such as Eclipse or IntelliJ) will auto-generate a lot of it for you. I still think it's a lot of boiler-plate though, which is why I prefer Scala—but that's a whole different discussion.
Edit:
My post grew so long that I lost track of why I wanted to introduce getters and setters. The point is that by encapsulating access to the field you're able to do something more like what you had in Python:
public class Test {
// Same as above . . .
}
class Subclass extends Test {
private int subclassItem = 1;
public int getItem() {
return subclassItem;
}
public void setItem(int item) {
this.subclassItem = item;
}
}
Now the item field has effectively been overridden since all access to it is done through the getter and setter, and those have been overridden to point at the new field. However, this still results in 0 1 in the output rather than the 1 1 you were expecting.
This odd behavior stems from the fact that you're printing from within the constructor—meaning the object hasn't actually been fully initialized yet. This is especially dangerous if a this reference is passed outside the constructor during construction because it can result in outside code accessing an incomplete object.
You could overload the superclass constructor to initialise the field item in Test to 0:
public class Test {
int item = 0;
Test(){
System.out.println(this.item);
}
Test(int item) {
this.item = item;
System.out.println(this.item);
}
void test(){
System.out.println(this.item);
}
public static void main(String[] args){
Subclass s = new Subclass();
s.test();
}
}
class Subclass extends Test {
public Subclass() {
super(1);
}
}
Use an initializer instead of redeclaring the fields:
public class Test {
int item = 0;
...
}
public class Subclass extends Test {
{
item = 1;
}
}
Note: depending on your package structure, you might want to declare item as protected.
I am trying to do something I would not normally do, it is a bit odd, but I'd like to make it work. Essentially I have a factory that has to create objects by calling the constructor with different types of data (A and B take different types in the code below). I seem to have gotten my self stuck going down the generics route (I do need the code to be as compile time typesafe as possible). I am not opposed to writing the code differently (I'd like to keep the idea of the factory if possible, and I do not want to have to add in casts - so the "data" parameter cannot be an "Object").
Any thoughts on how to fix the code with generics or an alternative way of doing it that meets my requirements?
(Technically this is homework, but I am the instructor trying out something new... so it isn't really homework :-)
public class Main2
{
public static void main(String[] args)
{
X<?> x;
x = XFactory.makeX(0, "Hello");
x.foo();
x = XFactory.makeX(1, Integer.valueOf(42));
x.foo();
}
}
class XFactory
{
public static <T> X<T> makeX(final int i,
final T data)
{
final X<T> x;
if(i == 0)
{
// compiler error: cannot find symbol constructor A(T)
x = new A(data);
}
else
{
// compiler error: cannot find symbol constructor B(T)
x = new B(data);
}
return (x);
}
}
interface X<T>
{
void foo();
}
class A
implements X<String>
{
A(final String s)
{
}
public void foo()
{
System.out.println("A.foo");
}
}
class B
implements X<Integer>
{
B(final Integer i)
{
}
public void foo()
{
System.out.println("B.foo");
}
}
I don't see a way to make it work. I don't really think it should work either. When calling your makeX() function the calling code needs to know what integer parameter corresponds to what type of data to pass in. IOW, your abstraction is very leaky in the first place, and what you're really implementing is a rudimentary form of polymorphism, which you might as well use method overloading for, i.e.:
X makeX(String data) {
return new A(data);
}
X makeX(Integer data) {
return new B(data);
}
Of course it's a toy problem and all that. One way to make it work would be to make the client aware of implementation classes and add a Class<T> argument that you instantiate through reflection. But I suppose that would be kind of defeating the purpose.
I don't think what you're trying to do is possible without casting.
With casting, you have two options
if(i == 0)
{
x = new A((Integer)data);
}
else
{
x = new B((String)data);
}
}
or
class A
implements X<String>
{
A(final Object s)
{
}
}
...
class B
implements X<Integer>
{
B(final Object i)
{
}
}
Probably the closest thing you could get whilst retaining static type safety and having lazy construction is:
public static void main(String[] args) {
X<?> x;
x = aFactory("Hello").makeX();
x.foo();
x = bFactory(42).makeX();
x.foo();
}
private static XFactory aFactory(final String value) {
return new XFactory() { public X<?> makeX() {
return new A(value);
}};
}
public static XFactory bFactory(final Integer value) {
return new XFactory() { public X<?> makeX() {
return new B(value);
}};
}
interface XFactory() {
X<?> makeX();
}
So we create an instance of an abstract factory that creates the appropriate instance with the appropriate argument. As a factory, the product is only constructed on demand.
Clearly something had to give. What would you expect XFactory.makeX(1, "Hello") to do?
This is not possible without casting. As I have said elsewhere - generics don't remove the need for casting, but they mean that you can do all the casting in one place.
In the setup you describe, the factory method is exactly where all the under-the-hood work takes place. It's the spot where your code tells the compiler "I know you don't know what these types are, but I do, so relax.
It's entirely legit for your factory method to know that if i==1, then the data must be be of type Integer, and to check/enforce this with casting.