Is it possible to have perform method overloading in different classes.
class Parent{
// Private method
private void method1(){
System.out.println("In private method of Parent class");
}
void method2(){
}
void method3(){
}
}
class Child extends Parent{
void method3(int i){
}
}
To perform overloading it is necessary to have two methods of same name and with different signature in the class. but in inheritance how does it work.
In inheritance is it true that copy of non private method is created in the child class?
In this example overloading is performed or not?
Overloading means methods with same name but different signature but not override equivalent for particular class. It's subject of class and not related to it's parent or child. Moreover, if parent has overloaded methods than child may or may not have the same behavior. Moreover, if any interface contains the overloaded signatures your class ultimately have the overloaded methods.
Note here that you have not overloaded method3(int i) with method() of parent, even more method of Child is not related to method of it's parent in your case. You can only override non-private and non-static methods of parent but you can not overload them, there is no meaning of overloading them.
Overriding - Redefining the methods in the Sub Class with out disturbing the signature. This is also called as Dynamic Binding, which will be decided during Runtime based upon the object being passed.
Overloading - Redefining the methods with in the same Class by changing the method signatures. This is also called as Static Binding, which will be decided during compile time.
Here, in your particular example, we SHOULD NOT say that the method3() is overloaded as we did not re-define method3() more than one time with in the same class.
Related
Well, I have learned that method overriding is done in non-static methods while method hiding is done for a static method. So what is the difference between them if in method overriding the method of child class is overriding the parent class method so that only method which is of child class is executed?
While in method hiding the same thing is happening that the child class method is hiding the parent class method so that only the child class method is executing?
In the code, I provide below the output of both the program is the same so what is the difference between overriding and hiding.
The difference can be seen by the code #SMA already mentioned:
public static final void main(String... strings) {
final Child obj = new MainClass.Child();
obj.f1();
final Parent p = obj;
p.f1();
}
will lead to:
Child class
Child class
Whereas the static alternative will lead to:
Child class
Parent class
So in the overriding case the parent method can only be called from the overriding method any more. Whereas in the static case the hidden method still exists and will be called when the corresponding context (hence the parent class) is used.
(I know calling static methods through instances of the class is not a good practice, but it helps to illustrate the answer to this question.)
Is the show() method in class B 'overridden', 'implemented' or simply 'defined'?
interface A
{
void show();
}
class B implements A
{
public void show()
{
System.out.println("What is the proper term to explain?");
}
}
A short answer, we override those methods, why?
Because this represents the concept of polymorphic statement, Remember
List<String> aa = new ArrayList<>();
// List => interface
// ArrayList => class
aa.add("polymorphic statment");
Polymorphic statement and overiding go hand in hand.
Although any class also has the option to implement an interface by declaring itself abstract and no need to override any method.
Note: Apply the same concept in any IDE, will guide you to add #Override annotation.
Generally speaking I say "override" to mean redefining an inherited behavior and I keep "implement" to mean defining a behavior (not implemented yet).
So I would say that B implements show().
And the JLS seems to go in this way :
If a non-abstract method mC overrides an abstract method mA from a
class C, then mC is said to implement mA from C.
The oracle example documentation seems to says that override is to redefine a behavior too :
The ability of a subclass to override a method allows a class to
inherit from a superclass whose behavior is "close enough" and then to
modify behavior as needed. The overriding method has the same name,
number and type of parameters, and return type as the method that it
overrides. An overriding method can also return a subtype of the type
returned by the overridden method. This subtype is called a covariant
return type.
Note that the java.lang.Override annotation doesn't say the contrary (emphasis is mine) :
Indicates that a method declaration is intended to override a method
declaration in a supertype. If a method is annotated with this
annotation type compilers are required to generate an error message
unless at least one of the following conditions hold:
The method does override or implement a method declared in a
supertype.
The method has a signature that is override-equivalent to that of any
public method declared in Object.
The API could have provided #Implement additionally to the #Override annotation.
But it seems rather clumsy to have both. So they probably kept a single one : #Override to convey the two things.
The method show() in class B implements the method declared in interface A.
You should say implement because override means that you are overwriting some existing method which is not true in case of interfaces. Interfaces cannot contain method definitions, they merely specify a contract.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
overriding case:
class a{ public void m() {} }
class b extends a { #override public void m(){} }
hiding case :
class a { public static void m(){} }
class b extends a{ public static void m(){} }
is this one instance method hiding another?
interface i { void m(); }
interface j { void m(); }
class a implements i,j { void m(){} }
Can a instance method hide another instance method?
Static methods
In case of static methods you'd have to provide the class to the call anyways (they are class methods, not instance methods) and thus there'd be no hiding, e.g.
A.m(); //call static method on class A (btw, Java convention is that class names start with a capital case letter)
B.m();
Instance methods
Instance methods can't hide others, just override them, e.g. if B extends A, whenever you call m() on an instance of B, then the B version of m() would be called.
Interfaces
In case of interfaces you'd implement a method once even if it is declared in multiple interfaces.
As of Java 8 where there might be default implementations of interface methods and IIRC a concrete implementation would override the default implementation whereas two default implementations interfaces I and J would generate a compile time error (unless one interface is more specific, e.g. if J extended I.
class a { public static void m(){} }
class b { public static void m(){} }
These classes don't share a common ancestor, so one can't "hide" the other's method. In Java, same-name instance methods in subclasses always override the superclass's instance method, there is no hiding mechanism as there is in other languages (such as Pascal if I remember correctly). This is true even if the #Override annotation isn't made, the annotation just makes code more readable and helps against typos.
If you changed class b to extend class a, however, then it's static method m() would in fact hide the same name method in a.
This is what the Oracle docs have to say about this:
The distinction between hiding a static method and overriding an instance method has important implications:
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
In the case of your interfaces:
interface i { void m(); }
interface j { void m(); }
class a implements i,j { void m(){} }
Interfaces don't provide any instance methods themselves, they are just a contract that the implementing class has to honor by implementing the methods declared in the interface. In your case, both your interfaces simply require the implementing classes (like class a) to implement a method public void m(). It's like promising both your wife and your daughter to take them out for ice cream on Saturday - the promise made to your daughter doesn't invalidate, hide or negate the same promise made to your wife. ;)
So in short: instance methods cannot be hidden in Java.
As a side note: Per the Java naming conventions, classes and interfaces should start with upper case letters.
If the method matches both signatures in i and j (which is here the case), it implements them both. If the signatures in the two interfaces don't differ enough to use overloading, they can not be combined into a single class.
There is no hiding/overriding when it comes to interfaces, only implementation.
For interfaces i and j, if a class implements both then that is fine, there is no violation of the interface.
For static methods, you can't hide it as you have to call it from the class i.e. a.m() and b.m(), hence it is not hidden.
Lastly for overriding methods, the method of the superclass isn't hidden, it is overridden.
Defining a Method with the Same Signature as a Superclass's Method
In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
In the case of #Override it's ok.
The interface case is different:
An interface define a contract it just say that the object marked as the interface can do something. Without defining how to do it. So you aren't hiding the method, but with the class that implements two interfaces you're defining that two action (with the same name) are executed in the same way.
I know Constructors are not inheritable in java, we need to use super() - super must be the first statement in Constructors.
But why cant i use #Override annotation?
In example:
public class Foo extends Point2D.Double {
#Override // The annotation #Override is disallowed for this location
public Foo(){}
}
If i have a instance of Foo, i never ever can call Point2D.Double.Double() directly! This behave is compleatly like Overriding!
#Override is used when you are overriding a method (not a constructor!), which means that you are creating a method using the same name and parameters as one of the methods from superclass.
There is no constructor called Foo() in your superclass (obviously), because constructors aren't inherited from parent classes, so this is not overriding.
Overriding can be only applied to inherited methods which are not constructors and are not defined as final.
You cannot override a constructor.
Constructors are not inherited.
Yous subclasses constructor is completely different and independent from super class's constructor (language semantically, due to initializations etc it may depend. ).
While you can call super() to call the super class's constructor it's called chaining not overriding.
Because there is no previous implementation of Foo of which will be overridden.
#Override is denoted the place where override supper class(Parent class) method in child class. Constructor is NOT a method and can't override in that way. So you can't put #Override there.
Compiler checks overriding rules while compiling the java class. Constructors cannot be overridden so compiler generates an error if somebody tries to use #Override annotation for the constructor.
Because you do not ovverride a constructor. As you state constructors are not inheritable. Defining a constructor in a Subclass is not the same process as ovverriding a method. Therefore the JVM invokes automatically super(), or you have to do it yourself, when you define a constructor in a Subclass, which is not required when ovverriding a method.
You could override only when you have a method in your parent class. Since parent class does not have Foo() method.. hence no override is allowed.
I believe you are not asking about overriding a constructor like
public class Foo extends Point2D.Double {
public Double(){
}
}
this is simply not allowed. However, each subclass constructor has to chain either to another constructor within the subclass or to a constructor in the superclass. So for example:
public class Superclass
{
public Superclass(int x) {}
public Superclass(String y) {}
}
public class Subclass extends Superclass
{
public Subclass()
{
super(5); // chain to Superclass(int) constructor
}
}
The implication of constructors not being inherited is that you can't do this:
// Invalid
Subclass x = new Subclass("hello");
The case is that you do not perform override at all. That is why you can not use that annotation. When you declare the a new constructor you are assured that super() will be called by Java. You do not have to force it. What more you can not apply any additional operation before the super(). This lead to the conclusion that if you need to call default constructor from parent class you do not have to do anything special.
The case change when you enforce to use some parameterized constructor, then you have to add that call in child class. But if your parent class has no default constructor then you will always need to call that parameterized.
I have an abstract class A
I have about 10 classes that extend A
Class A has one or two static methods and it makes sense that these are static, because they belong to the 10 classes, NOT instances of them. One static method e.g. is called getAllFromX, which gets all all instances of the class from X, whatever that may be, it may be a server, well it actually is, but it doesn't matter. So you see it makes sense these methods are static and are not bound to an instance.
At the same time class A has a NON-static abstract method, each subclass overrides this method (just returns a string). I cannot make it static because static methods cannot be overridden (...).
To summarize: abstract class A has a static method and a abstract non-static method, that is overriden by the subclasses. I cannot make the second method static because it must be overriden. On the otherhand I could make the first method non-static, but it would be very ugly and bad programming style, so I'll leave it that way.
The catch? The static method in class A must get the value the non-static method returns (for the subclass the static method is inherited from, of course).
Is the "easiest" way to use reflection to get this done? I mean...really?
Like e.g., I get the class the static method is in:
Class<?> cl=new Object(){}.getClass().getEnclosingClass(); (a hack I found here, thank god...)
I then use getConstructor to construct an object of this subclass.
And then I use this object to call the non-static method.
Really?? Can it not be done easier? I mean that is if I want to design my program conceptually correct...
Coming from C# I don't like that (and the type erasure thing). It is just ugly. Doable but ugly. And a big stumbling block, at least for beginners. EDIT: after reading it again, I'd add: /rant end. Sorry, but I actually care.
I think what you in fact need is the following:
public class A {
public static Set<A> getAllFromX() {
...
}
}
public class B extends A {
public static Set<B> getAllFromX() {
...
}
}
public class C extends A {
public static Set<C> getAllFromX() {
...
}
}
(Just as the valueOf() and values() methods in enums, which is redefined in every Enum subclass, because static methods can't be inherited)
In this case, each class has its own static method doing whatever it wants. But your question doesn't make much sense because it says:
The static method in class A must get the value the non-static method returns (for the subclass the static method is inherited from, of course).
Indeed, the static method is not inherited by the subclass. Static methods are never inherited. If you define a static method foo() in A, and call
B.foo();
the compiler doesn't refuse to compile it, but it translates it to
A.foo();
So, there's no way to do in foo() something that depends on the class on which foo() is called, since it's always A.
You can always use reflection to invoke a method using class name e.g.
Object objectX = ClassX.class.newInstance();
//get your method passing argument types as second param
Method method = ClassX.class.getDeclaredMethod("methodX", null);
//invoke your method passing arguments as second param
method.invoke(objectX, null);
Since you mentioned your static method doesn't use any instance but you are using reflection to get the instance hence I am really not sure, how does it fit in your requirement though.
I think making it as an implemented method (non-static) in your abstract class is a better choice. That way you implement it once but its available in in all your 10 extending classes.
I think your problem is one of larger design. A different object should be responsible for retrieving instances of A or its subclasses. As you can see, relying on a static method to be replaced by subclasses does not work well. Without knowing more about the problem domain, it's hard to give a good answer, but I would consider something similar to the Abstract Factory pattern.
Broadly speaking: Define an abstract class, AFactory, with a method Collection getInstances(). Extend AFactory for each of the concrete subclasses of A you need to return and implement that logic in the overridden getInstances() method as appropriate. You may also provide a static method on the abstract AFactory, getFactory(Class), to get the appropriate factory subtype at runtime.