George Vargas
George Vargas

Reputation: 13

Method for all objects that extend the same class?

Let say I have 3 classes that all extend the same class...

public class Foo {
     private String name;
     ...
}
public class FooExtend1 extends Foo {
     ...
}
public class FooExtend2 extends Foo {
     ...
}
public class FooExtend3 extends Foo {
     ...
}

then I create a util function that changes the property that implements from Foo...

public void changeName(??? param1) {
     param1.setName("");
}

and I want param1 to be all objects that extends from the Foo class.

Would I have to overload the method or is there another way?

Upvotes: 0

Views: 613

Answers (2)

Turing85
Turing85

Reputation: 20205

We do not need to override the method since the inheritance-relationship between the types grants the capabilites of implicit widening conversion from sub- to supertype (see JLS, §5.1.5). Thus, we can rewrite the method to

public void changeName(Foo param1) {
     param1.setName("");
}

Ideone demo (I took the liberty and set the name in the utility method to "foo" so we can see that the method works in the demo output)

This works as expected, given that Foo has a method public String setName(String).


A remark: I would suggest renaming method changeName(...) to something more expressive, e.g. setEmptyName(...) or resetNameToDefault(...).

Upvotes: 3

Oleksandr Cherniaiev
Oleksandr Cherniaiev

Reputation: 813

Your method defined in parent is accessible for all its children:

public void changeName(String param1) {
     this.name = param1;
}

If you want to have method in some class outside:

public void changeName(Foo foo, String newName) {
     foo.setName(newName);
}

and you can pass any Foo descendant there.

Upvotes: 0

Related Questions