View RSS Feed

Java Object

Using Name Hiding for Overriding

Rate this Entry
by , 11-30-2011 at 03:45 AM (1186 Views)
Sometimes you will have a java base class that has a method thatís been overloaded several times. It is important for the programmer to remember that redefining the method name in the derived class does not hide any of the base-class versions. Therefore you should keep in mind that overloading works irrespective of whether the method has been defined at this level or in a base class:

Java Code:
import static com.acme.examples.Print.*;

public class Mother {
	char foo(char c) {
		print("foo(char)"); 
		return 98; // character b
		} 
	
	float foo(float f) {
		print("foo(float)"); 
		return 1.0f;
		}
}

import static com.acme.examples.Print.*;

public class Daughter extends Mother {
	
	void foo(OurHouse m) {
	print("foo(OurHouse)");
	}
}

public class OurHouse {

}


public class Hide {
	public static void main(String[] args) {
		Daughter d = new Daughter(); 
		d.foo(1); 
		d.foo('x'); 
		d.foo(1.0f);
		d.foo(new OurHouse());
	}
}
You can see that all the overloaded methods of Mother are available in Daughter, even though Daughter has a new overloaded method. Itís very common to override methods with the same name, the same signature and returning the same type as in the base class. Since java 5 has added the @Override annotation, which is not a keyword but can be used as though it was. So now when you want to override a method, you can add this annotation and the compiler will produce an error message if you overload instead of overriding.

Submit "Using Name Hiding for Overriding" to Facebook Submit "Using Name Hiding for Overriding" to Digg Submit "Using Name Hiding for Overriding" to del.icio.us Submit "Using Name Hiding for Overriding" to StumbleUpon Submit "Using Name Hiding for Overriding" to Google

Comments