hhh3112
hhh3112

Reputation: 2187

Class casting unclarity

I have the following abstract class:

public abstract class AbstractGroup {

private String name;
.
.
.
}

I have two empty classes that extend this abstract class:

public class GroupA extends AbstractGroup {
}

public class GroupB extends AbstractGroup {
}

Is there a way to cast the following without getting a ClassCastException: (group is of type GroupA)

group = (GroupB)group;

I need this object instance to become GroupB.

Upvotes: 1

Views: 137

Answers (6)

Vedant Agarwala
Vedant Agarwala

Reputation: 18819

Possible if you do something like:

    GroupA groupAobj = new GroupA();
    AbstractGroup abstractObj = (AbstractGroup) groupAobj;
    GroupB groupBobj = (GroupB) abstractObj;

the code compiles and runs.

Upvotes: -1

Marko Topolnik
Marko Topolnik

Reputation: 200148

What you are asking for is not called casting, but conversion. Both terms are covered by the umbrella term coercion. Java will not convert an object for you automatically and it couldn't even if it tried since this is generally an ill-defined problem. You must write your own code that will do the conversion -- either in the form of a conversion constructor, or some static conversion method, or maybe an instance method in the source object that returns the converted object.

Upvotes: 1

Ahmad
Ahmad

Reputation: 2190

No, you can't. You can cast up or down on Inheritance hierarchy.

Upvotes: 1

gzm0
gzm0

Reputation: 14842

No you cannot, because a GroupA is not an instance of GroupB. How about:

public abstract class AbstractGroup {

  public Enum Group { GroupA, GroupB; }

  private String name;
  private Group membership;
.
.
.
}

And then:

group.setMembership(GroupB);

Upvotes: 1

luketorjussen
luketorjussen

Reputation: 3264

No it isn't possible. But what you may like to do is add some constructor to the Groups to allow construction from a different implementation.

public class GroupA extends AbstractGroup {
    public GroupA(AbstractGroup otherGroup) {
        this.name = otherGroup.name;
    }
}

However if you find yourself needing to do this then perhaps your design may be wrong.

Upvotes: 0

Adam Sznajder
Adam Sznajder

Reputation: 9206

It's not possible. You cannot cast classes horizontally but only vertically. GroupA is not the subtype of GroupB so the exception always will be raised.

Upvotes: 10

Related Questions