Replace inheritance with delegation
The Replace Inheritance With Delegation refactoring lets you remove a class from inheritance hierarchy, while preserving the functionality of the parent. IntelliJ IDEA creates a private inner class, that inherits the former superclass or interface. Selected methods of the parent are invoked via the new inner class.
Select a class you want to refactor.
On the main menu, or on the context menu, select
.In the dialog that opens, specify parent object, the name of the inner class definition. Also, select the members of the parent class that will be delegated through the inner class, and getter options.
Preview and apply changes.
Example
Before | After |
---|---|
// File Class.java
public class Class extends SuperClass {
public int varInt;
public void openMethod() {
...
}
}
// File SuperClass.java
public abstract class SuperClass {
public static final int CONSTANT=0;
public abstract void openMethod();
public void secretMethod() {
...
}
}
|
// File Class.java
public class Class {
public int varInt;
private final MySuperClass superClass = new MySuperClass();
public SuperClass getSuperClass() {
return superClass;
}
public void openMethod() {
superClass.openMethod();
}
private class MySuperClass extends SuperClass {
public void openMethod() {
...
}
}
}
// File SuperClass.java UNCHANGED
public abstract class SuperClass {
public static final int CONSTANT=0;
public abstract void openMethod();
public void secretMethod() {
...
}
}
|
Last modified: 02 August 2022