Avoid derived class to override a method yet should allow callers toinvoke the method

E

Ethan

Hello,

I have a requirement where base class has method (implemented) and
derived class shouldn't be able to override it.
However, the method needs to be invoked by a caller who creates an
instance of the derived class.

Is this possible?
 
L

Lew

Ethan said:
I have a requirement where base class has method (implemented) and
derived class shouldn't be able to override it.
However, the method needs to be invoked by a caller who creates an
instance of the derived class.

Is this possible?

Absolutely.

You prevent an override by 'final' in the method signature, and this is very frequently The Right Thing To Do.

You make the method callable by client code through 'public' in the method signature, which is the standard thing to do.

public class BaseOfOperations
{
public final void DoSomething()
{
// implementation here
}
}

public class SpecificOperations extends BaseOfOperations
{
// cannot override DoSomething()
}

public class Client
{
public void Whatever()
{
BaseOfOperations boo = new SpecificOperations();
boo.DoSomething();
}
}

I suggest that you read the Java tutorials and a good basic book on Java programming.
http://download.oracle.com/javase/tutorial/
 
E

Ethan

Absolutely.

You prevent an override by 'final' in the method signature, and this is very frequently The Right Thing To Do.  

You make the method callable by client code through 'public' in the method signature, which is the standard thing to do.

public class BaseOfOperations
{
  public final void DoSomething()
  {
    // implementation here
  }

}

public class SpecificOperations extends BaseOfOperations
{
  // cannot override DoSomething()

}

public class Client
{
  public void Whatever()
  {
    BaseOfOperations boo = new SpecificOperations();
    boo.DoSomething();
  }

}

I suggest that you read the Java tutorials and a good basic book on Java programming.http://download.oracle.com/javase/tutorial/

Thanks Lew and Peter. Its been a while that i have coded in java and
didn't knew much about final.
 
A

Andreas Leitgeb

Lew said:
public class BaseOfOperations {
public final void DoSomething()
public class Client {
public void Whatever()

Method names should not begin with capital letters.
Not even in trivial example snippets.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top