View RSS Feed

My Java Tips

Extract superclass

Rate this Entry
by , 11-20-2011 at 06:49 PM (1706 Views)
Inheritance is a very useful feature that object oriented languages provide. Normally you write parent class first and then the child class. When the design of the application is not final, you tend to put more code in a class than required. At some instance, you realize, that you may make a super class and put some methods in it. Eclipse provide an easy way to do this.


Lets take an example. We have following class:


Java Code:
public class CSVFile{

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}	

	public ArrayList extractHeader() {
		return null;
	}

	public int getNoOfRows() {
		return 0;
	}

	public ArrayList extractContents() {
		return null;
	}

}
We realised that extractHeader, extractContents and getNoOfRows should be in super class and CSVFile should inherit from it. We can do that by creating a new class and copying the code from CSVFile class.

Simple way is to use Eclipse Refactor feature.

Eclipse provides a way to extract the super class from a class. Right click the class name from package explorer. Select Refactor > Extract super class.




Really simple way. The super class will be generated and the methods will be removed from the child class and will be available in the superclass.

Java Code:
import java.util.ArrayList;

public class SuperClass {

	public SuperClass() {
		super();
	}

	public ArrayList extractHeader() {
		return null;
	}

	public int getNoOfRows() {
		return 0;
	}

	public ArrayList extractContents() {
		return null;
	}

}

public class CSVFile extends SuperClass{

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

Submit "Extract superclass" to Facebook Submit "Extract superclass" to Digg Submit "Extract superclass" to del.icio.us Submit "Extract superclass" to StumbleUpon Submit "Extract superclass" to Google

Comments