Can a subclass override a method and have different parameters? - java

I want to have a method in multiple subclasses which essentially get a certain thing done (like getting user info), but is declared in (and has different parameters and definitions than) the main class. Is this possible?
I know this is not really overriding, but can this be done or is it not a suitable way to structure methods?

What you want to do is called overloading a method. It is doable and occurs often. Play with the fiddle here. Java is similar.
public class Parent
{
public virtual string HelloWorld()
{
return "Hello world";
}
public string GoodbyeWorld()
{
return "Goodbye world";
}
}
public class Child : Parent
{
// override: exact same signature, parent method must be virtual
public override string HelloWorld()
{
return "Hello World from Child";
}
// overload: same name, different order of parameter types
public string GoodbyeWorld(string name)
{
return GoodbyeWorld() + " from " + name;
}
}
public class Program
{
public static void Main()
{
var parent = new Parent();
var child = new Child();
Console.WriteLine(parent.HelloWorld());
Console.WriteLine(child.HelloWorld());
Console.WriteLine(child.GoodbyeWorld());
Console.WriteLine(child.GoodbyeWorld("Shaun"));
}
}

You can have multiple versions of a method with the same name having different number of parameters. You can have all these in the main/parent class or you can add the newer versions in the subclasses only. There is no restriction on doing this.

As stated in the comments and the other answer, you can define a method in a subclass with the same name as a method in its superclass, but you can't override it, exactly. Both methods will still exist, so it's called overloading. In Java and in C Sharp it works pretty much the same; you just define a new method with different parameters. You cannot just change the return type, though. The parameters to the methods must be different in order to overload one. Here is an article about overloading vs. overriding in Java.

Related

Why is this final variable null? [duplicate]

I have a Wicket page class that sets the page title depending on the result of an abstract method.
public abstract class BasicPage extends WebPage {
public BasicPage() {
add(new Label("title", getTitle()));
}
protected abstract String getTitle();
}
NetBeans warns me with the message "Overridable method call in constructor", but what should be wrong with it? The only alternative I can imagine is to pass the results of otherwise abstract methods to the super constructor in subclasses. But that could be hard to read with many parameters.
On invoking overridable method from constructors
Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the #Override is invoked, the state of the object may be inconsistent and/or incomplete.
A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
Here's an example to illustrate:
public class ConstructorCallsOverride {
public static void main(String[] args) {
abstract class Base {
Base() {
overrideMe();
}
abstract void overrideMe();
}
class Child extends Base {
final int x;
Child(int x) {
this.x = x;
}
#Override
void overrideMe() {
System.out.println(x);
}
}
new Child(42); // prints "0"
}
}
Here, when Base constructor calls overrideMe, Child has not finished initializing the final int x, and the method gets the wrong value. This will almost certainly lead to bugs and errors.
Related questions
Calling an Overridden Method from a Parent-Class Constructor
State of Derived class object when Base class constructor calls overridden method in Java
Using abstract init() function in abstract class’s constructor
See also
FindBugs - Uninitialized read of field method called from constructor of superclass
On object construction with many parameters
Constructors with many parameters can lead to poor readability, and better alternatives exist.
Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:
Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...
The telescoping constructor pattern is essentially something like this:
public class Telescope {
final String name;
final int levels;
final boolean isAdjustable;
public Telescope(String name) {
this(name, 5);
}
public Telescope(String name, int levels) {
this(name, levels, false);
}
public Telescope(String name, int levels, boolean isAdjustable) {
this.name = name;
this.levels = levels;
this.isAdjustable = isAdjustable;
}
}
And now you can do any of the following:
new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);
You can't, however, currently set only the name and isAdjustable, and leaving levels at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean and int arguments, which would really make a mess out of things.
As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).
Bloch recommends using a builder pattern, which would allow you to write something like this instead:
Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();
Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.
See also
Wikipedia/Builder pattern
Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters (excerpt online)
Related questions
When would you use the Builder Pattern?
Is this a well known design pattern? What is its name?
Here's an example which helps to understand this:
public class Main {
static abstract class A {
abstract void foo();
A() {
System.out.println("Constructing A");
foo();
}
}
static class C extends A {
C() {
System.out.println("Constructing C");
}
void foo() {
System.out.println("Using C");
}
}
public static void main(String[] args) {
C c = new C();
}
}
If you run this code, you get the following output:
Constructing A
Using C
Constructing C
You see? foo() makes use of C before C's constructor has been run. If foo() requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo() expects, you get a warning.
Invoking an overridable method in the constructor allows subclasses to subvert the code, so you can't guarantee that it works anymore. That's why you get a warning.
In your example, what happens if a subclass overrides getTitle() and returns null ?
To "fix" this, you can use a factory method instead of a constructor, it's a common pattern of objects instanciation.
Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.
class A {
protected int minWeeklySalary;
protected int maxWeeklySalary;
protected static final int MIN = 1000;
protected static final int MAX = 2000;
public A() {
setSalaryRange();
}
protected void setSalaryRange() {
throw new RuntimeException("not implemented");
}
public void pr() {
System.out.println("minWeeklySalary: " + minWeeklySalary);
System.out.println("maxWeeklySalary: " + maxWeeklySalary);
}
}
class B extends A {
private int factor = 1;
public B(int _factor) {
this.factor = _factor;
}
#Override
protected void setSalaryRange() {
this.minWeeklySalary = MIN * this.factor;
this.maxWeeklySalary = MAX * this.factor;
}
}
public static void main(String[] args) {
B b = new B(2);
b.pr();
}
The result would actually be:
minWeeklySalary: 0
maxWeeklySalary: 0
This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.
I hope that would help someone.
If you call methods in your constructor that subclasses override, it means you are less likely to be referencing variables that don’t exist yet if you divide your initialization logically between the constructor and the method.
Have a look on this sample link http://www.javapractices.com/topic/TopicAction.do?Id=215
I certainly agree that there are cases where it is better not to call some methods from a constructor.
Making them private takes away all doubt: "You shall not pass".
However, what if you DO want to keep things open.
It's not just the access modifier that is the real problem, as I tried to explain here. To be completely honest, private is a clear showstopper where protected usually will still allow a (harmful) workaround.
A more general advice:
don't start threads from your constructor
don't read files from your constructor
don't call APIs or services from your constructor
don't load data from a database from your constructor
don't parse json or xml documents from your constructor
Don't do so (in)directly from your constructor. That includes doing any of these actions from a private/protected function which is called by the constructor.
Calling an start() method from your constructor could certainly be a red flag.
Instead, you should provide a public init(), start() or connect() method. And leave the responsibility to the consumer.
Simply put, you want to separate the moment of "preparation" from the "ignition".
if a constructor can be extended then it shouldn't self-ignite.
If it self-ignites then it risks being launched before being fully constructed.
After all, some day more preparation could be added in the constructor of a subclass. And you don't have any control over the order of execution of the constructor of a super class.
PS: consider implementing the Closeable interface along with it.
In the specific case of Wicket: This is the very reason why I asked the Wicket
devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.
Construction - via constructor
Initialization - via onInitilize (after construction when virtual methods work!)
There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)
The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.
I guess for Wicket it's better to call add method in the onInitialize() (see components lifecycle) :
public abstract class BasicPage extends WebPage {
public BasicPage() {
}
#Override
public void onInitialize() {
add(new Label("title", getTitle()));
}
protected abstract String getTitle();
}

Why is the output in the last row "Wuff Ringding" ? and not "Ringding Ringding"?

Hey guys can you help me wih my code. Its about polymorphism. I have just a question about the last row of the main function. Where is the output there "Wuff Ringding" and not "Ringding Ringding" ?
public class Hund{
public Hund (){
}
public String belllen(){
return "Wuff";
}
public String spielen(Hund h){
return "Wuff" + h.bellen();
}
}
public class Fuchs extends Hund{
public Fuchs (){
}
public String bellen(){
return "Ringding";
}
public String spielen(Fuchs f){
return "Ringding" + f.bellen();
}
}
public class Park {
public static void main (Strin[] args){
Hund bello = new Hund();
Fuchs foxi = new Fuchs();
Hund hybrid = new Fuchs();
System.out.println(hybrid.spielen(foxi));// Output is Wuff Ringding
System.out.println(foxi.spielen(hybrid)); // Output is Wuff Ringding
}}
Java has dynamic method dispatch, but it is only a single dispatch based on the runtime type of the object whose method you are invoking. There is no dynamic dispatch based on the runtime types of the arguments, instead the method (if there are multiple overloaded methods to choose from) is selected at compile-time based on the declared types.
foxi.spielen(hybrid)
foxi is known to be a Fuchs. You have the following overloaded methods
public String spielen(Hund h); (inherited from Hund)
public String spielen(Fuchs f); (declared on Fuchs)
hybrid is declared to be a Hund, so the first method will be called. It does not matter that it is actually a Fuchs at runtime. You'd get to the second method with foxi.spielen((Fuchs)hybrid).
Maybe you intended to override instead of overloading the method? Then it would indeed have printed your expected result. But that did not happen, because to override a method, you have to match the parameter types exactly. If you intend to override a method, you should use the annotation #Override which will alert you have such mistakes.

When we override a method we should use all the parameters that are in the method signature?

I found some overrides methods that not use all the parameters that are in the signature of the method.
ex:
#Override
protected void setSomething(Object a, Object b, Object c) {
this.a = a
this.b = b;
// the parameter c is not used (ignored)
}
Normally the parent class shouldn't be care about how the children will implements the abstract methods.
But in MHO, arguments of a method are to be use, it's very rare when a sub-class implementation doesn't need a parameter, when this happens then probably there's a problem with the design of the interface or with the abstract class.
The base of one function is: inputs -> process of inputs -> output.
Sometimes you need to calculate these inputs, but if you don't go to use some of these inputs in the process of your function, these inputs shouldn't be place as inputs of your function.
You could jump the calculation of these inputs calling an accurate function that use all the inputs, so the accurate function.
The only case where this situation could be acceptable, is when we don't want the behavior of the parent class, so we could write:
#Override
protected void setSomething(Object a, Object b, Object c) {
//Nothing to do
}
Or
#Override
protected void setSomething(Object a, Object b, Object c) {
throw new UnsupportedOperationException(...);
}
Sonar says :
Unused parameters are misleading. Whatever the value passed to such
parameters is, the behavior will be the same.
My Question is:
When we override a method we should use all the parameters that are in the method signature?
When I says 'use all the parameters', I try to say that all the parameters that are in the method signature, are really use in the body (implementation) of the method.
When we override a method we should use all the parameters that are in the signature of the method?
When you override a method, the overriden method must define the same parameters as the super-method.
You're not obligated to use all the parameters in the implementation - this depends on what you want to achieve with this implementation and sometimes not all parameters may be needed.
However, having unused method parameters within the method implementation is a sign of a poor design. When defining a method (being abstract or implemented), you should try answer the questions of "Why would I need this parameter?" and "Will this parameter be always used?". If it's possible to have cases where some parameters will not be used in the implementation, then you could define a few overloaded methods.
Take this example, for instance. Let's have this method
void someMethod(String first, String optionalParameter) { ... }
The second parameter is optional (i.e. may be needed or may not be) - you could pass null or anything when the parameter is not needed. In this case, I would overload two methods
void someMethod(String first) { ... }
void someMethod(String first, String second) { ... }
and I will also make sure that all the parameters are used in the corresponding implementation.
Do you need to use all the parameters? No. You will often see examples like:
#Override
public void doFoo(String thingy) {
// no-op
}
Or
#Override
public void doFoo(String thingy) {
throw new UnsupportedOperationException(...);
}
But both are a sign of questionable design, somewhere. java.util.List or even java.util.Iterable, for example, both preclude the possibility of an immutable collection, by providing mutation methods. Immutable implementations have to throw UnsupportedOperationException.
If you override a method, than yes, you must use all the parameters.
But you can also overload a method - write a method with same name but different parameters. So if you dont use all of the parameters, you are overloading, not overriding.
class Accessor {
public void doSomething(String attr) {}
}
class Child extends Accessor {
// This is overriding
#Override
public void doSomething(String attr) {
// ...
}
// This is overloading
public void doSomething() {
// ...
}
}
As you said: "we should" - but we don't have to. Sometimes an implemnting method even throws a RuntimeException, e.g. UnsupportedOperationException of the Java Collections Framework.

Variable Inheritance in Java

I have a Super class and a bunch of subclasses. I want to have one field that has the same name in every single subclass, but I do not want it to be defined in the super class, or at least I do not want to use that value. This is what I have right now
public abstract class Big {
public String tellMe = "BIG";
public Big() {}
public void theMethod() {
System.out.println ("Big was here: " + tellMe() + ", " + tellMe);
}
public String tellMe() {
return tellMe;
}
}
public class Little extends Big{
public String tellMe = "little";
public Little(){}
public String tellMe() {
return "told you";
}
public static void main(String [] args) {
Little l = new Little();
l.theMethod();
}
}
When I run Little, this is the output
Big was here: told you, BIG
I am not sure why 'told you' is printed out while tellMe refers to "BIG". How can both be true?
My problem is that I want the method tellMe() to be in Big, and to have the variable tellMe (that it will actually return) to be defined in all the subclasses. The only way I can get this to work is as I have written, by rewriting the tellMe() method in each subclass. But doesn't that defeat the whole purpose of inheritance??? Please help
EDIT: I do not use the constructor in my subclasses. All I want is a field that can be set in all subclasses and a method in the super that uses those values. I don't understand why this isn't possible because every subclass would have to implement it, so it would make sense... If this simply is not possible, let me know please
Fields are not virtual, unlike methods. For this reason, it is a bad idea to declare fields with the same name as a field in another class in the hierarchy. The field referred to in theMethod is always going to be from Big (i.e. when you declare a field with the same name, it just hides the old field when in the scope of the replacing class, but doesn't replace it).
One solution would be to override a method that gets the field from the current class:
In theMethod replace the tellMe field with getTellMe() and for all classes override getTellMe() to return the correct value (or the field that hides the superclass's field).
You can overwrite the value of Big.tellMe in the constructor of Little.
get rid of:
public String tellMe = "little";
and change the Little constructor to:
public Little(){
tellMe = "little";
}
at that point, you can get rid of Little.tellMe() also.
What you are doing is hiding the super class field, not overriding it, as the Java documentation states.
And it's also stated that it's not a good idea to do it.
So, the dynamic lookup won't work as for a method. If the variable is read from the son class, it will take "its" field value.
On the top class, the other one.
What you can override in Java is the behaviour, so what I would suggest is to
define a method
public String tellMe() {
return "Whatever";
}
that you can override in the subclasses to return whatever string you need.
Instead of defining tellMe inside of Big (since you said you do not want to define/use that value in Big) you can create a function in Big:
public abstract String tellMeString();
And define that in each subclass like so (for Little):
public String tellMeString()
{
return "Little";
}
Then theMethod can execute:
System.out.println ("Big was here: " + tellMe() + ", " + tellMeString());
In this case you wouldn't have to define a variable "tellMe" at all, you just override tellMeString in each subclass to return different Strings.
Fields are not inherited as you are expected. You can access the super class' field (unless it is private) from subclass. But you cannot "override" field. This is why tellMe used by method implemented in super class Big uses variable defined in the same class.
If you want inheritance use methods. For example you can implement method "tellMe()" that returns "BIG" in super class and "little" in subclass:
class Big {
protected String tellMe() {
return "BIG";
}
}
class Little {
#Override
protected String tellMe() {
return "Little";
}
}
Alternatively you can initialize variable tellMe in constructor:
class Big {
private String tellMe;
public Big() {
this("BIG");
}
protected Big(String tellMe) {
this.tellMe = tellMe;
}
protected String tellMe() {
return "BIG";
}
}
class Little {
public Little() {
super("Little");
}
}
Now new Little().tellMe() will return "Little": the variable in super class was initialized when constructing the object; the method defined in super class returned this variable.
Methods can be overridden, fields are visible at the scope where they're called.
static class Big {
String field = "BIG";
String bark() { return "(big bark)"; }
void doIt() {
System.out.format("field(%s) bark(%s)\n", field,bark());
}
void doIt2() {
System.out.format("2:field(%s) bark(%s)\n", field,bark());
}
}
static class Small extends Big {
String field = "small";
String bark() { return "(small bark)"; }
void doIt2() {
System.out.format("2:field(%s) bark(%s)\n", field,bark());
}
}
public static void main(String... args) {
Big b = new Big();
b.doIt();
b.doIt2();
Small s = new Small();
s.doIt();
s.doIt2();
}
Output is:
field(BIG) bark((big bark))
2:field(BIG) bark((big bark))
field(BIG) bark((small bark))
2:field(small) bark((small bark))
since doIt() is defined in the Big class, it will always see the Big version of field. doIt2() is defined in Big, but overridden in Small. The Big.doIt2() sees the Big version of field, the Small.doIt2() version sees the Small version of field.
As others have pointed out, it's a pretty bad idea to do this - a better approach is to set the new value in the subclass constructor, or to use a method which is overridden.

is this possible in java or any other programming language

public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
System.out.println ("Parameters for subclass method were: ....");
}
}
public class Owner extends Master {
public void printSomething () {
System.out.println ("This printed from Owner");
}
public int returnSomeCals ()
{
return 5+5;
}
}
Without messing with methods of subclass...is it possible to execute printForAllMethodsInSubClass() before the method of a subclass gets executed?
update:
Using AspectJ/Ruby/Python...etc
Would it also be possible to print the parameters? Above code formatted below:
public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
}
}
public class Owner extends Master {
public void printSomething (String something) {
System.out.println (something + " printed from Owner");
}
public int returnSomeCals (int x, int y)
{
return x+y;
}
}
AspectJ can provide this functionality for you, but it's a separate compilation step and some extra libraries involved.
public aspect ServerLogger {
pointcut printSomething ();
before(): printSomething()
{
(Master)(thisJoinPointStaticPart.getTarget()).printForAlMethodsInSubClass();
}
}
The Eclipse Project provides a great implementation of AspectJ that integrates nicely with Eclipse and Maven. There's a boatload of great documentation available for it, and a lot of really good material for it here on StackOverflow.
[update]
To access parameter info, you can use the
thisJoinPoint.getSignature();
method to access information about the function being called if the returned Object is an instance of MethodSignature, you can use Signature.getParameterNames() to access the parameters to the function being called. You'd have to use a bit of reflection to actually get at the values, I think - AspectJ doesn't seem to handle this for you. I'd have to actually do some experimentation to get some working code for you.
To answer the "any other programming language": It's easily possible in Ruby:
class Master
REDEFINED = []
def printForAllMethodsInSubClass
puts 'Printing before subclass method executes'
end
def self.method_added(meth)
if self < Master and not Master::REDEFINED.include? meth
new_name = "MASTER_OVERRIDE_#{meth}".intern
Master::REDEFINED.push meth, new_name
alias_method new_name, meth
define_method(meth) {|*args| printForAllMethodsInSubClass; send(new_name, *args)}
end
end
end
You could also make a proxy declaration method to use in subclasses:
class Master
def printForAllMethodsInSubClass
Printing before subclass method executes
end
def self.master_method(name)
define_method(name) {|*args| printForAllMethodsInSubClass; yield *args}
end
end
class Owner
master_method(:print_something) do
puts "This was printed from Owner"
end
end
(This approach would also translate very naturally to Python decorators.)
This is possible in aspect-oriented programming languages, such as AspectJ.
In Python you can accomplish this using meta classes, here's a small example. You can probably make it more elegantly but it is just to make the point
import types
class PrintMetaClass(type):
def __init__(cls, name, bases, attrs):
# for every member in the class
override = {}
for attr in attrs:
member = attrs[attr]
# if it's a function
if type(member) == types.FunctionType:
# we wrap it
def wrapped(*args, **kwargs):
print 'before any method'
return member(*args, **kwargs)
override[attr] = wrapped
super(PrintMetaClass, cls).__init__(name, bases, attrs)
for attr in override:
setattr(cls, attr, override[attr])
class Foo:
__metaclass__ = PrintMetaClass
def do_something(self):
print 2
class Bar(Foo):
def do_something_else(self):
print 3
In this example, the PrintMetaClass gets in the way of the creation of the Foo class and any of its subclasses redefining every method to be a wrapper of the original and printing a given message at the beginning. The Bar class receives this aspect-like behavior simply by inheriting from Foo which defines its __metaclass__ to be PrintMetaClass.
Metaclasess in OOP:
http://en.wikipedia.org/wiki/Metaclass
Metaclasses in python:
http://www.python.org/doc/essays/metaclasses/
http://www.ibm.com/developerworks/linux/library/l-pymeta.html
Besides aspect oriented programming have a look at Template Method Pattern, http://en.wikipedia.org/wiki/Template_method_pattern.
In short: the parent class have an abstract method, which subclasses have to implement, this abstract method is called by a method in the parent class where put your printouts or whatever necessary statements.

Categories