Method overriding with different parameters - java

Lets say I have a parent class:
class Parent{
public void aMethod() {
//Some stuff
}
}
and it's child class:
class Child extends Parent {
public void aMethod(int number){
//Some other stuff
}
}
Now the child has both methods with different parameters. This does method overloading. But I need method overriding, i.e, If someone tries to call aMethod() with the object of child class then the method of child class should be called or say method of parent class should not be accessible. But I can't change the access modifier of the parent class because the parent class has other children as well and they need the method as is.
So any suggestions?

You can override the Parent's method in the Child class and throw an exception:
class Child extends Parent {
public void aMethod(int number){
//Some other stuff
}
#Override
public void aMethod() {
throw new UnsupportedOperationException();
}
}
Or, if you want the existing method of the Child class to be executed :
class Child extends Parent {
public void aMethod(int number){
//Some other stuff
}
#Override
public void aMethod() {
aMethod (someIntValue);
}
}
Either way Parent's implementation of aMethod() will never be executed for instances of class Child.

this
void aMethod() {
and this
void aMethod(int number)
are totally different methods (their signature is different) so there is not way to say that aMethod(int number) is overriding aMethod()
so what you can do?:
override the only method you can and the OVERLOAD it
public class Child extends Parent {
#Override
public void aMethod() {
// TODDY
}
//here overload it
public void aMethod(int number){
// TODDY
}
}

You can implement a version of aMethod in the Child class and it will be called instead of the parent's version when you call that method on any instance of the Child class.
You don't need to change the Parent's signature to override the method because both public and protected methods can be overridden.
class Child extends Parent {
#Override
public void aMethod() {
// TODO
}
public void aMethod(int number){
//Some other stuff
}
}

Related

Template method pattern issue

if I have an abstract Parent class which has a templateMethod and a concrete Child class :
abstract class Parent
{
final void templateMethod()
{
foo();
}
abstract void foo();
}
class Child extends Parent
{
#Override
void foo()
{
System.out.println("foo");
}
}
what should i do if i only want the user to know that templateMethod and do not want to expose foo method to class Child's user while let the Child class define the implementation of foo method ?
Or, is template method not suitable in this case? Then, is there any other strategies i can use?
As suggested by JB Nizet in the comment, you could do:
abstract class Parent {
final void templateMethod() {
foo();
}
abstract protected void foo();
}
class Child extends Parent {
#Override
protected void foo() {
System.out.println("foo");
}
}
Since Parent.foo() is protected, only subclasses of Parent can call the method.
You might also find this question helpful: What is the difference between public, protected, package-private and private in Java?

How to create a java method on a base class that calls other methods?

I'm trying to build a base class with a method that needs to call a private method before and after performing the actual logic.
public abstract class Base {
public Base() {}
private void before() {
// doSomething
}
private void after() {
// doSomething
}
public void actual(Object object) {
before();
// doSomething
after();
}
}
public class SomeClass extends Base {
public SomeClass() {}
public void actual(Object object) {
// actual code that needs to be executed between before and after methods.
}
}
How would I go about this?
Create another method that can be overridden and implemented instead of overriding actual directly.
E.g.
public void actual(Object object) {
before();
doActual(object);
after();
}
protected abstract void doActual(Object object);
You could make the actual() method final if you want to ensure that nobody overrides it by mistake.
You can make the method as abstract e.g.
protected abstract void actual(Object object);
and create another public method which is going to be called
public void init(Object object){
before();
actual(object);
after();
}

could parent object be created using super to call parent method

Would the parent object be created , if we use the super keyword to call the method of the parent class in child object?
Outcomes show that both Mybase and MySub have the same reference address. Not sure whether it is a good demo.
class Mybase {
public void address() {
System.out.println("super:" + this);
System.out.println( this.getClass().getName());
}
}
class MySub extends Mybase {
public void address() {
System.out.println("this:" + this);
System.out.println( this.getClass().getName());
}
public void info() {
System.out.println("this:" + this);
super.address();
}
}
public class SuperTest {
public static void main(String[] args) {
new MySub().info();
}
}
Well, let's find out!
Your test isn't quite going to answer your question. If you want to see if an object is created, why not create a constructor that prints to the console when called?
public class Test {
static class Parent {
Parent() {
System.out.println("Parent constructor called");
}
void method() {
System.out.println("Parent method called");
}
}
static class Child extends Parent {
Child() {
System.out.println("Child constructor called");
}
#Override
void method() {
System.out.println("Child method called");
super.method();
}
}
public static void main(final String[] args) {
new Child().method();
}
}
If you run this, you get this output:
Parent constructor called
Child constructor called
Child method called
Parent method called
So as you can see, when method() was called, no Parent object was created when the super keyword was used. So the answer to your question is "no".
The reason is because super and super() are different. super (no parentheses) is used to access members of the parent class. super() (with parentheses) is a call to the parent constructor, and is only valid inside a constructor as the first call in the constructor. So using super (no parentheses) will not create a new object.
Also, super() doesn't actually create a new, independent Parent object. It just does the initialization work for the fields of Parent that is needed before the child constructor continues.

Identifying the child class calling a base class static function

Suppose I have a base class with a function foo
public class Base
{
protected static void foo()
{
// ToDo - what is the name of the child class calling me?
}
}
and at least one child class containing a static initialiser that calls foo
public class Child extends Base
{
static
{
foo();
}
}
Is there a way of foo() knowing which child class has called it? I'm presuming there's a reflection technique I can use.
The simplest way is to pass an argument. For example
public class Base {
protected static void foo(Class<?> type) {
if (type == Child.class) {
}
}
}
public class Child extends Base {
static {
foo(Child.class);
}
}
However, if you need to do something that depends on the child class then I recommend looking for a solution that leverages abstract methods and polymorphism.
public Base {
protected static void foo(Base child) {
child.doFoo();
}
protected abstract void doFoo();
}
public Child extends Base {
static {
foo(new Child());
}
#Override
protected void doFoo() {
//do the child specific thing here
}
}
You can get the class by using the getClass method, like:
o.getClass()
also, if you have a class c and you need to check whether o is an instance of c, you can use instanceof, like this:
o instanceof c
Cheers.

Overwriting methods: how to "inject" into the super-method?

Assuming three classes, one being a subclass of the other. Each overwrite the parents' method.
public class BaseClass {
public void doStuff() {
performBaseTasks();
}
}
public class MiddleClass extends BaseClass {
// {BaseClass} Overrides
public void doStuff() {
performMiddleTasks();
super.doStuff();
}
}
public class FinalClass extends MiddleClass {
// {BaseClass} Overrides
public void doStuff() {
performFinalTasks();
super.doStuff();
}
}
When calling new FinalClass().doStuff(), this would lead to a method
invokation order as follows:
performFinalTasks();
performMiddleTasks();
performBaseTasks();
I want to bring the perfomFinalTasks() between performMiddleTasks() and
performBaseTasks(). How can I do this?
performMiddleTasks();
performFinalTasks();
performBaseTasks();
Write a public method in final class doStuffDifferently() and invoke these methods in that order. I am not sure it's possible to do it via any other tricks in the doStuff() method.
One possible way, if you can make the middle class abstract:
public abstract class MiddleClass extends BaseClass {
// {BaseClass} Overrides
public void doStuff() {
performMiddleTasks();
doProxyExec();
super.doStuff();
}
public abstract void doProxyExec();
}
You override the proxy method in your subclass:
public class FinalClass extends MiddleClass {
// {BaseClass} Overrides
public void doStuff() {
super.doStuff();
}
// {MiddleClass} Overrides
public void doProxyExec(
performFinalTasks();
}
}
A not very polymorphic way of method call chaining, but then again the original design is kind of ... odd.

Categories