Would syntax for composition be a useful addition to Java? [closed]

First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above

The idea would give composition the same ease of code reuse that extends does.

So if you had a class like this:

public interface A {  
    public void methodInA();  

And then you had a class like this:

public class B {  
    private composed A;
    public B() {
        // construct A within constructor

You would then be able to do this:

B myB = new B();

Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:

public void methodInA(){
    // B's own delegation method

Disadvantages include:

  • methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with extends
  • if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)
  • if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to
  • probably 100 other things I've not thought of

Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.

Asked by: Richard113 | Posted: 23-01-2022

Answer 1

It sounds cool but I think it makes for some horrible language constructs. Obviously there is a problem if you declare more than one 'composition' of the same class, but even if you forbid that what about the case where a call matches a method in more than one of the (different) composed classes? You would have to specify which one was called in the main class, and you would need extra syntax for that. The situation becomes even worse if there are public members in the classes.

Composition is used to prevent problems with multiple inheritance. Allowing composition like this is effectively permitting multiple inheritance, at least in terms of resolving which method to call. Since a key design decision with Java was to disallow multiple inheritance (for good reasons) I think it unlikely that this would ever be introduced to Java.

Answered by: Haris844 | Posted: 24-02-2022

Answer 2

I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.

Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's Effective Java, Favor composition over inheritence. I think that something like this would make it a little easier to implement the idiom he recommends in that item.

Honestly, if you really knew what you were doing I'll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this:

public class Foo {

  private Bar bar;

  // initialize bar via constructor or setter

Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren't already implemented by Foo would end up being generated to look like this:

public Baz method1(Qux val) {
  return bar.method1(val);

As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you'd probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it.

Now that I've written this out that seems kinda cool. Maybe I'll play around with it next week. I'll update this if I manage to figure anything out.

Answered by: Melissa858 | Posted: 24-02-2022

Answer 3

I'm not sure that I see a clear advantage to doing this though. I understand the point you are making. At the moment to call a method on A you have to myB.getAInstance().methodInA(), but you want to make that myB.methodInA().

But, what happens if you have multiple instances of A? How would the method call be resolved? Many times composition implies a one to many association so B has many A instances. What happens then?

I agree with your disadvantages listed. It may simply cause too much confusion than it is worth.

Answered by: Miranda770 | Posted: 24-02-2022

Answer 4

Check out what is called "Mixins" in some languages, and "Roles" in the Perl 5 Moose OO system.

Answered by: Kelvin173 | Posted: 24-02-2022

Answer 5

There's also the difference between composition and aggregation to consider. How does the compiler know whether you mean 'is-a' or 'has-a' relationships?

  • Does the whole object graph become eligible for garbage collection or only the head of the graph?

A couple of the ORM mapping tools and frameworks over/around them provide for belongsTo or has-many relationships between persistent objects and some also provide for the cascading delete (for composition). I don't know of one off hand that provides the simple syntactic sugar you're looking for.

Actually, on second thought, Groovy's MetaClass and MetaProgramming idiom(s) may provide something very similar, with 'auto-magic' delegation.

Answered by: Vivian247 | Posted: 24-02-2022

Answer 6

Multiple inheritance is allowed in C++, I know that different but it is along the same thought process. Java was designed to not allow multiple inheritance so that there would be less confusion, therefore bugs and exploits.

What you have suggested is in direct conflict with the principles of java.

Having said that, it would be cool (not necessarily useful). I'm a java programmer who switched from C++. I like being able to make my own mistakes.

Answered by: Patrick820 | Posted: 24-02-2022

Similar questions

inheritance - Java composition question

A question about composition and object orientation: I am trying to implement more features for a class (Java TreeMap as an example). public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable Using composition is the

java - Inheritance though composition?

Closed. This question needs details or clarity. It ...

java - Inheritance vs Composition?

I asked similar question one month ago: Inheritance though composition? I took the examples from this article: http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html?page=1 However, this time is a diff...

java - Difference between Inheritance and Composition?

This question already has answers here:

java - Inheritance vs Composition

This question already has answers here:

java - Inheritance vs Composition for canvas shapes model?

For the following model, would you prefer inheritance or composition: I want to draw objects on a canvas that each represent a data object think of it like a state machine diagram: Ellipses represent States, Lines represent connections/transitions between them. The object representation itself will never change, ie a State ...

java - game character class design, inheritance or composition?

I am trying to create the character class for a game. About the character class: -It has different characters, for example warrior, shooter, king. -Each has different properties for example attack, defense. My question here is should I use Inheritance or composition? I have a Character Class, then should I create warrior class and extends character class or should I just put an identifier like String ID ="W...

java - change inheritance to composition for existing jaxb class structure keeping the current xml structure unchanged

In my code base I have B extdnds A but I want to make it: B uses A. This is my try: @XmlAccessorType(XmlAccessType.NONE) public class A { @XmlElement(name ="aString") private String aString; B class contains A (composition): @XmlAccessorType(XmlAccessType.NONE) public class B { @XmlElement private A a = new A(); // has A @Xml...

inheritance - Java code for composition

Closed. This question needs to be more focused. It ...

java - Bounded Priority Queue Inheritance vs Composition

I want to write a Bounded Priority Queue class. This is essentially a priority queue but has a bound on the number of elements that can be there in the queue. So, if I insert a new element and the queue is full, then I see if the element is greater than the top of the queue. If yes, then I discard the new element. If no, then I remove the top element and insert this new element (and the queue gets automatically reorganized...

Good reasons to prohibit inheritance in Java?

What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?

inheritance - Java dynamic binding and method overriding

Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java. And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing... Here's the problem I was given: /* What is the ou...

Java Listener inheritance

I have a java class which fires custom java events. The structure of the code is the following: public class AEvent extends EventObject { ... } public interface AListener extends EventListener { public void event1(AEvent event); } public class A { public synchronized void addAListener(AListener l) { .. } public synchronized void removeAListener(AListener l) { .. } protected void fireA...

inheritance - Extending enum in Java

public enum myEnum { VAL1(10), VAL2(20), VAL3("hai") { public Object getValue() { return this.strVal; } public String showMsg() { return "This is your msg!"; } }; String strVal; Integer intVal; public Object getValue() { return this.intVal; } private myEnum(int i) { this.intVal = new Integer(i); } private myE...

inheritance - Java Protected Access Not Working

In java, there's three levels of access: Public - Open to the world Private - Open only to the class Protected - Open only to the class and its subclasses (inheritance). So why does the java compiler allow this to happen? TestBlah.java: public class TestBlah { public static void main(String[] args) { Blah a = new Blah("Blah"); Bloo...

inheritance - "Dynamic" Casting in Java

Hullo all, Wondering if there are any Java hackers who can clue me in at to why the following doesn't work: public class Parent { public Parent copy() { Parent aCopy = new Parent(); ... return aCopy; } } public class ChildN extends Parent { ... } public class Driver { public static void main(String[] args) { ChildN orig = new ChildN(); ... ...

java - Class inheritance with Hibernate and hbm2java

I am generating my domain objects from my hbm files with hbm2java and now I want them to all inherit a base class. This class will have some utility methods for dealing with listeners. It does not really need to be persisted and I am hoping that I would not have to do a hbm file for it since it will be abstract and only have methods. Is there a meta tag or something to have all generated class extend another class?

Abstract classes and methods in Java, Inheritance

I have class B, which inherits from class A. The superclass A is abstract, containing one abstract method. I don't want to implement the abstract method in class B, therefore I need to declare class B as abstract as well. Declaring class B abstract, two things are working for me (the programs compile and run correctly): 1.) I don't declare any abstract methods in class B, even thought the class is abstract. This wo...

inheritance - Java not inheriting accessor methods?

Given a class "Bar" that extends class "Foo" which implements interface "DeeDum" public interface DeeDum { public String getDee(); public String getDum(); } public class Foo implements DeeDum { public String dee = "D"; public String dum; public String getDee() { return dee; } public String getDum() { return dum; } } public class Bar extends Foo { public String dee = "DEE"; ...

How to by-pass inheritance in java when invoking a method

class Super { public void anotherMethod(String s) { retValue(s) } public String retValue(String s) { return "Super " + s; } } class Sub extends Super { public void anotherMethod(String s) { retValue(s) } public String retValue(String s) { return "Sub " + s; } }

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)