Take a look at the following code sample :
public class Test{
public static void main(String[] args){
System.out.println(new Test());
System.out.println(new Test(){
public String toString(){
return "manual override";
}
});
System.out.println(new Test(){
public String gm(){
return "manual gm";
}
}.gm());
} //end of main method
public String gm(){
return "gm";
}
}
There may be some argument that the toString() method is being overridden in anonymous inner class which is an entirely different class.
But the overriding code still resides in the same class. So, will it be justified to conclude that in some situations [as described above] , the overriding of a method in same class is possible?
Firstly, you haven't defined toString in your Test.java class.
Secondly, when you make a anonymous class, its is conceptually like creating a subclass. So overriding in anonymous class is allowed as long as parent method is not final.
Mainly, overriding is NOT possible in same class otherwise.
The answer is No, you cannot override the same method in one class. The anonymous inner class is a different class.
The code above overrides toString() method of Object class. So you cannot say that it overrides in the same class. Now also it is overriding a superclass method and here the super class is Object which is the super class of all classes.
No , You can override a method in subclass only.
public String toString(){
return "manual override";
}
In your case you are overriding Object's toString() method not Test class method.
In one class we can not have method with same signature.
this is because there is no need to have override method in same class.
hence overriding method in same class is not possible, where as if we want to use same method name we can overload method by changing signature.
About the "real world use case," I do find a practical usage of the above program in section 2.5 of "JUnit Recipes" 2005 by Manning.
public class Counter {
private int count;
// a simple integer instance variable
public Counter( ) { }
// default constructor (count is 0)
public Counter(int initial) { count = initial; }
// an alternate constructor
public int getCount( ) { return count; }
// an accessor method
public void increment( ) { count++; }
// an update method
public void increment(int delta) { count += delta; }
// an update method
public void reset( ) { count = 0; }
// an update method
}
Isn;t this function overriding under same class??
Related
I'm extending from an abstract class named ChildClass, it has 4 constructors which should be implemented.
There is a set of general configuration common to all constructors.
I could abstract these tasks and call it in all constructors.
Is there anyway to call a specif method when an object is going to be initialized rather than calling it in all of the constructor signatures?
Since Java compiler must ensure a call to a constructor of the base class, you can place the common code in a constructor of your abstract base class:
abstract class BaseClass {
protected BaseClass(/*put arguments here*/) {
// Code that is common to all child classes
}
}
class ChildClassOne extends BaseClass {
public ChildClassOne(/*put arguments here*/) {
super(arg1, arg2, ...);
// More code here
}
}
As already stated in the comment, one way to call common initialization code would be the use of this(...), i.e. you'd call one constructor from another. The problem, however, is that this call would have to be the first statement of a constructor and thus might not provide what you want.
Alternatively you could call some initialization method (the most common name would be init()) in all constructors and in a place that is appropriate (e.g. at the end of the constructor). There is one problem though: if a subclass would override that method it could create undefined situations where the super constructor calls the method and the method uses non-yet-initialized fields of the subclass. To mitigate that the method should not be overridable, i.e. declare it final or make it private (I'd prefer to have it final though because that's more explicit).
Depending on your needs there's a 3rd option: use the initializer block:
class Super {
{
//this is the initializer block that is called before the corresponding constructors
//are called so it might or might not fit your needs
}
}
Here's an example combining all 3 options:
static class Super {
{
//called before any of the Super constructors
System.out.println( "Super initializer" );
}
private final void init() {
System.out.println( "Super init method" );
}
public Super() {
System.out.println( "Super common constructor" );
}
public Super(String name) {
this(); //needs to be the first statement if used
System.out.println( "Super name constructor" );
init(); //can be called anywhere
}
}
static class Sub extends Super {
{
//called before any of the Sub constructors
System.out.println( "Sub initializer" );
}
private final void init() {
System.out.println( "Sub init method" );
}
public Sub() {
System.out.println( "Sub common constructor" );
}
public Sub(String name) {
super( name ); //needs to be the first statement if used, calls the corrsponding Super constructor
System.out.println( "Sub name constructor" );
init(); //can be called anywhere
}
}
If you now call new Sub("some name"), you'll get the following output:
Super initializer
Super common constructor
Super name constructor
Super init method
Sub initializer
Sub name constructor
Sub init method
You can declare an instance method in the class which can be called from a constructor like this:
Class A{
public A(){
initialize();
}
public void initialize(){
//code goes here
}
}
This concept extends to abstract classes as well.
You could chain your constructors.
public class Test {
public Test() {
// Common initialisations.
}
public Test(String stuff) {
// Call the one ^
this();
// Something else.
}
You can then put your common code in the () constructor.
An alternative is to use an Initializer block.
Class A {
{
// initialize your instance here...
}
// rest of the class...
}
The compiler will make sure the initializer code is called before any of the constructors.
However, I would hesitate a bit to use this use this - perhaps only if there are no other alternatives possible (like putting the code in a base class).
If you can put the common code in one constructor and call it as the first instruction from the other constructors, it is the Java idiomatic way.
If your use case is more complex, you can call a specific method from the constructors provided it is private, final or static (non overidable). An example use case would be:
class Test {
private final void init(int i, String str) {
// do common initialization
}
public Test(int i) {
String str;
// do complex operations to compute str
init(i, str); // this() would not be allowed here, because not 1st statement
}
public Test(int i, String str) {
init(i, str);
}
}
Make a common method and assign it to instance variable. Another way of doing it.
import java.util.List;
public class Test {
int i = commonMethod(1);
Test() {
System.out.println("Inside default constructor");
}
Test(int i) {
System.out.println("Inside argument Constructor ");
}
public int commonMethod(int i) {
System.out.println("Inside commonMethod");
return i;
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test(2);
}
}
Why It calls base class method when we declare method as static in base as well as in derive class and do upcasting.
class Base
{
static void show(){
System.out.println("Base class....");
}
}
class Derive extends Base
{
static void show(){
System.out.println("Drive class....");
}//method hidding.....
public static void main(String[] args)
{
Base b= new Derive();
b.show();
}
}
There are several issues here to mention:
static methods are not inherited and not overridden by the sub-classes
static methods do not need an instance to be called, they need a class
So, basically, calling b.show(); actually means calling Base.show();
You're calling Base.show, not Derive.show. Method hiding is not overriding.
§8.4.8.2. of the Java Language Specification gives an example that demonstrates exactly what happens here:
A class (static) method that is hidden can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods. The example:
class Super {
static String greeting() { return "Goodnight"; }
String name() { return "Richard"; }
}
class Sub extends Super {
static String greeting() { return "Hello"; }
String name() { return "Dick"; }
}
class Test {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());
}
}
produces the output:
Goodnight, Dick
because the invocation of greeting uses the type of s, namely Super, to figure out, at compile time, which class method to invoke, whereas the invocation of name uses the class of s, namely Sub, to figure out, at run-time, which instance method to invoke.
Just one more completion to the answers above. It's best to invoke class methods by their class not by an instance variable: Base.show() not b.show() to make clear that the method is a static method. This is especially useful in your case when you are hiding a method, not overriding it.
Hi I am facing a design problem which I think it should be quite common:
public abstract class Parent
{
...
public boolean itsOk()
{
return true;
}
public void execute()
{
if (itsOk()){
System.out.println("done");
}
}
}
I need to be able to override itsOK() function in any subclass inherited from 'Parent' even if arguments are different.
public class Example extends Parent
{
public boolean itsOK(int a)
{
if (a==1) return true;
else return false;
}
}
Then when I call execute, I want the subclass' itsOk() method to be invoked.
public static void main(String[] args) {
Example e=new Example();
e.execute();
}
This works ok if the subclass' itsOk() method has no arguments (like the 'Parent's method), so it's an overriding case, but how can I make it when arguments are different?
Call super.itsOk(); in your subclass' itsOk method.
That is, I'm assuming what you mean is you want to have an overload of itsOk defined in your subclass which does something new but also invokes the parent class' default implementation of itsOk.
As an aside, note the terminology: you're not overriding: to do that, the itsOk in your subclass must have the same method signature as in the parent class. Instead you're overloading creating a brand new method that just happens to have the same name.
You can use generics:
public abstract class Parent
{
...
public <T> boolean itsOk(T t)
{
return true;
}
public void execute()
{
if (itsOk()){
System.out.println("done");
}
}
}
public class Example extends Parent<Integer>
{
public boolean itsOK(Integer a)
{
if (a==1) return true;
else return false;
}
}
In such a case I would rather try to have the same method signature in the parent and the child class, ie. a real overwriting and not an overloading. Then, your parameter a could be a member of the class Example which would avoid the need for a parameter. Of course it strongly depends on the rest of the code.
The itsOk(int a) method in class Example is not overriding the itsOk() method in class Parent - it is an entirely separate method that doesn't have anything to do with the method in class Parent.
With what value of a do you want itsOk(int a) in Example to be called when you call itsOk() in Parent?
You could ofcourse add an itsOk(int a) method to class Parent; then the version in Example would be overriding that version, and in the execute() method you could call it:
public abstract class Parent {
public boolean itsOk() {
return true;
}
public abstract boolean itsOk(int a);
public void execute() {
if (itsOk(0)) {
System.out.println("done");
}
}
}
Without declaring an itsOk(int a) method in class Parent, you cannot call that method on a Parent object (or on an Example object, if the type of the variable referring to the object is Parent).
I don't think this is a common design problem.
When arguments are different it no longer is a case of Overriding. It is called Overloading which basically means that you have two distinct methods to call.
interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() {
return "test";
}
});
}
}
What is the result?
A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.
What is the answer of this question and why? I have one more query regarding this question. In line 4 we are creating an object of A. Is it possible to create an object of an interface?
What you are seeing here is an anonymous inner class:
Given the following interface:
interface Inter {
public String getString();
}
You can create something like an instance of it like so:
Inter instance = new Inter() {
#Override
public String getString() {
return "HI";
}
};
Now, you have an instance of the interface you defined. But, you should note that what you have actually done is defined a class that implements the interface and instantiated the class at the same time.
test should be the output. This is an example of an anonymous inner class.
This is a very common pattern used with the Comparator interface as an emulation of closures.
Try this too... The name of anonymous class is generated!
Inter instance = new Inter() {
public String getString() {
return "HI" + this.getClass();
}
};
The trick is not only about the anonymous inner class, this prints test cause it overrides the toString method and while System.out.println a Object it implicit call it's toString method.
We can create an object of an anonymous class, that implements the interface:
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
If you have an interface, that declares one method toString, you can first create a class, that implements this inerface, and then create an object of this class:
interface TestA {
String toString();
}
class TestB implements TestA {
#Override
public String toString() {
return "test";
}
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestB());
}
}
Or you can create an object of an anonymous class to simplify this code:
interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
#Override
public String toString() {
return "test";
}
});
}
}
In both cases it prints "test".
I don't know the significance of this question. If this is an interview question, then I can say it's okay. But in real time it's not the right approach to implement an inheritance.So coming to the answer of the question, here what you are doing is an anonymous inner class .
Here you are instantiating a class and implementing the inheritance by writing,
System.out.println(new TestA() {
public String toString() {
return “test”;
}
});
and ofcourse the result would be test
Can an abstract class have a final method in Java?
Sure. Take a look at the Template method pattern for an example.
abstract class Game
{
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
Classes that extend Game would still need to implement all abstract methods, but they'd be unable to extend playOneGame because it is declared final.
An abstract class can also have methods that are neither abstract nor final, just regular methods. These methods must be implemented in the abstract class, but it's up to the implementer to decide whether extending classes need to override them or not.
Yes, it can. But the final method cannot be abstract itself (other non-final methods in the same class can be).
Yes, there may be "final" methods in "abstract" class.
But, any "abstract" method in the class can't be declared final.
It will give "illegal combination of modifiers: abstract and final" error.
public abstract final void show();
illegal combination of modifiers: abstract and final
Here is the working example of the implementation.
abstract class Sian //ABSTRACT CLASS
{
public final void show() // FINAL METHOD
{
System.out.println("Yes");
}
public void display()
{
System.out.println("Overriding");
}
public abstract void success();
}
class Ideone extends Sian //INHERTING ABSTRACT CLASS
{
public void display()
{
System.out.println("Overridden");
}
public void success() //OVERRIDING THE ABSTRACT METHOD
{
System.out.println("Success overriding");
}
public static void main (String[] args) throws java.lang.Exception
{
Ideone id = new Ideone(); //OBJECT OF SUBCLASS
id.show(); //CALLING FINAL METHOD
id.display(); //OVERRIDDEN METHODS
id.success();
}
}
OUTPUT:-
Yes
Overridden
Success overriding
Here is the ideone link:- http://ideone.com/G1UBR5
Yes.
Hint: just fire up your favorite IDE (eclipse, netbeans, etc) and try it out. It will complain if it does not work.
Yes.
Yes, those methods cannot be overriden in subclasses. An example of that is the template method pattern...
Yes it can ... need more characters
Of course, it means you can subclass it, but you cannot override that particular method.
Yes. The abstract modifier makes it possible to omit some of the implementation of a class (i.e. have some abstract methods) but does not impose any restrictions on you.
In Abstract Class methods may be defined or not. If we extend the abstract class then only it has meaning, so what ever methods we declare or defined in Abstract call it will over ride in subclass. So we can declare a method as final in Abstract class, and it will be over ridden in subclass.
Suppose I want to designed class which has some implementation but I do not want others(sub classes) to implement it but other methods, then in that case we need a final implemented method and obvious choice abstract class.
Yes, We can write the final method with implementation.
public abstract class AbstractWithfinalMethod {
public static final boolean m1() {
System.out.println(" M1 method executed");
return true;
}
public static void main(String[] args) {
System.out.println(m1());
}
}
output:
M1 method executed
true