Is this method overloading in java? - java

In the below code , can I say class B has overloaded add method ?
class A
{
public void add()
{
//some code
}
}
class B extends A
{
public void add(int a)
{
// some code
}
}

Nods
Yes, that's an example of method overloading. An example of method overriding would be,
class B extends A{
#Override
public void add(){
// do stuff
}
}

From the perspective of the API exposed by B, an add method already exists, even if provided by the superclass. Since you provide another add method with different arguments, this is overloading. To have provided the same signature would have been overriding.

Yes this is method overloading.

Yes. Consider this more straightforward example of overloading:
class A
{
public void add()
{
//some code
}
public void add(int a)
{
//this method is overloading add() from within its own class
}
}
Now, since B, in your example code extends A, it inherits add() and so it's safe to say that even though add() is not explicitly defined in B, the method is available, and so defining add(int a) may be considered overloading of add()

Yes, you can say that class B has overloaded the method add(). As public void add() is already present in class B, due to inheritance. Creating a method with same name, but a different signature (ie. the number, type, and order of the parameters) is overloading.

Related

Overriding method as varargs and Overridden method is normal method

public class DemoParent {
public void m1(int i) {
System.out.println("parent");
}
}
public class DemoChild extends DemoParent{
public void m1(int... i) {
System.out.println("child");
}
public static void main(String[] args) {
DemoParent p = new DemoChild();
p.m1(10);
DemoChild c = new DemoChild();
c.m1(10);
}
}
Here I have two class DemoParent and DemoChild which extends DemoParent, in DemoParent i have general method m1(int i) but in DemoChild i have varargs method m1(int... i). When i am creating object of child class and calling m1 method,it's giving me parent class method output. See below the output.
o/p- parent
parent
Can anyone explain me why parent class method is always calling from the Child class reference even if child has the same method?
but if we reverse the code i.e. parent class have varargs method and child has normal method then it will acts as an overloading instead of Overriding . So the output is
o/p - parent
child
but in the above 1st scenario i didn't understand why always parent class method is calling from child reference.
You're not overriding. You're overloading.
DemoChild has two methods called m1, and it has to choose which of the methods to invoke, based on the fact that you pass a single int as a parameter.
The non-varargs method will always be matched before the varargs overload, because the language spec rules around method invocation say that it will be (to preserve backwards compatibility with pre-varargs code).

Java sample Output Program

I wrote a program in Java with 2 interface and a class.
Both the interface has the same method name.
In the main class i am implementing both the interfaces and called the method.
I want to know which interface method is called...
Here is the sample code :-
public interface A {
void print();
}
public interface B {
void print();
}
public class C implements A, B {
public static void main(String[] args) {
C c = new C();
c.print();
}
public void print() {
System.out.println("sample");
}
}
public interface A {
void print();
}
public interface B {
void print();
}
In the above code the interfaces A and B are abstract interfaces, because some/all methods are declared but not defined.
Hence in your C class you are not calling any of these two (which is straightforward, how would you be able to call a method which was never defined?). What you are doing is defining the print method (hence giving it a body), to call it afterwards (in main).
You call the class's method
public void print() {
// TODO Auto-generated method stub
System.out.println("sample");
}
It's C's print(). abstract methods don't have implementations and are not called per se, it's one of their implementations that's called.
You may want to look into what's called static binding and dynamic binding. In this case to the compiler & runtime everything is at compile time, so the former is employed. Basically it will be statically determined that the method / implementation you want to call is C's print().
Dynamic binding would still mean calling a concrete implementation of a method, so it wouldn't choose an interface method per se, but the choice of which method to call will be done at runtime.
Interface which is implemented first in a way that interface's method will call and if another interface is next to the first one have same method name that will not going to call at all.

Can a method in sub class overloading a method in super class?

Java code:
class P {
public void hello() {}
}
class C extends P {
public void hello(String s) {}
}
My question is: Is the hello in class C overloading the one with same name in super class P?
My friend says they are not because the are not in the same class.
Taking a more formal approach, the Java Language Specification for Java 7 states:
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.9
I would point your friend to this link.
So, in short, in your example, the hello method is indeed overloaded.
Simple Explanation:
I think this question arises because at times we hear the following,
"Method overloading is performed within class.
Method overriding occurs in two classes that have inheritance relationship."
The above statement is correct. But your friend is wrong. why?
Because when you extend a class, the subclass have all the methods defined by superclass. It is as if all the methods of superclass have been implemented by the subclass. That means the hello() method has been implemented by the class C as well. Now, you added a method in class C with different parameter (hello(String s)). That means, class C has two methods in all with same name but different parameters and that is "overloading".
Hope it is crystal clear.
Overloading can happen in same class as well as parent-child class relationship whereas overriding happens only in an inheritance relationship.
Yes, your friend is wrong because he thinks only of the concept of overriding.
But here hello(), and hello(String s) are different by there parameters so it's overloading not overriding.
Source of confusion: Your friend would be right if speaking about C++ not Java. In C++, function overloading can only occur between members of the same class. Whereas in Java, overloading can occur, in addition to that, across two classes with inheritance relationship.
Yes it is overloading, This overloading is happening in case of the class 'C' which is extending P and hence having two methods with the same name but different parameters leading to overloading of method hello() in Class C. However Class P is only able to access one of the methods which is present in its own definition.
Long story short, an instance of C will have both the hello() and the hello(String s) methods available. An instance of P will only have the hello method available.
This is indeed overloading, as you have two methods of the same name taking different parameters.
However, it is not overriding, because overriding is having a method declared in a subclass with the same name and same parameters as a method in a superclass.
E.g. if you had
class C extends P {
public void hello() {}
}
it would be overriding the hello() method declared in P. When invoking new C().hello() in that case, you would invoke the implementation of the hello() method declared in class C.
It is a valid question since usually, overloading is explained using two methods with the same name (but different parameters) in the same class.
I would argue that yes, the method hello in C is overloading P's hello method because of the "is a" relation.
The "is a" relation states that since C subclasses P, it is also an instance of P ("C is a P"). Hence C has 2 overloaded hello-methods.
Good question!!!In sub class if method name | parameter type | list is changed then sub class method will not be considered as overriding it is considered as overloading method
Example :
class A{
void m1(int a){}
}
class B extends A{
void m1(float f)
{}
}
In above program m1 method is a overloaded method.
Yes we can overload the super class method in sub class like as bellow:
public class OverLoading {
public static void main(String[] args) {
B b = new B();
b.display();
b.display(4);
}
}
class A {
public void display() {
System.out.println("A class display method");
}
}
class B extends A {
public void display() {
System.out.println("class B subclass");
}
public void display(int a) { //Overloading in subclass
System.out.println("class B subclass with overloading");
}
}
Output:
class B subclass
class B subclass with overloading
Depends on the class. From class P's perspective (if the reference is P, the object can be of C) it is not. If you write something like: P p = new C(); there is no overloading because you cannot call p.hello("foo").
From class C's perspective it is overloaded because if you write C c = new C(); it has two methods with same name and different signatures.
This is a good question and the answer is a bit tricky.
Well, it's true that you can overload an inherited method from a parent class into a subclass. However, and here's the interesting part, the actual behavior depends on the reference variable type.
Let's consider the following example:
public class OverLoadingTest {
public static void main(String[] args) {
ChildClass cc = new ChildClass();
SuperClass sc = cc;
sc.method("lol");
cc.method("lol");
}
static class SuperClass {
public void method(Object o) {
System.out.println("SuperClass called.");
}
}
static class ChildClass extends SuperClass {
public void method(String s) {
System.out.println("ChildClass called.");
}
}
}
So, we have a class extending another and with a method that overloads a method from the parent.
It's easy to guess that if you have an instance of ChildClass, the two methods are overloaded, and overloading resolution takes place as it normally does.
However, let's consider creating an instance of ChildClass and assigning it to a reference variable of type SuperClass. Is the overloading thing still standing?
If you execute this program you will get this outptut:
SuperClass called.
ChildClass called.
The output clearly indicates that there's no overloading here in this case. This however can be altered by overriding the original method.
static class ChildClass extends SuperClass {
public void method(String s) {
System.out.println("ChildClass called.");
}
public void method(Object o) {
System.out.println("ChildClass called.");
}
}
Now, if you run the program again, you get this output:
ChildClass called.
ChildClass called.
Explanation
Now, why is JVM behaving that way? Why can't it see the overloading method as we're using an instance of the child class?
This takes us to how does JVM call a method. The JVM sees that you're referring to the object with a reference of type SuperClass, so, it can only use the methods that are related to that type, with the only exception is overriden methods. And since method(String) isn't overriding, we have method(Object) of the parent, hence, it's the one chosen for execution.
We then override the method to break this rule, and this is how the JVM called ChildClass.method(Object) even if the reference variable is of a parent class.
Overloading is when you have two methods that have the same name but different signatures (Your case).
Side note: Overriding is when you have two methods that have exactly the same signature and name and the parent class.

Can I override using subclass object as parameter in Java?

I have classes as follows
public class Useful
{
public void f(Object a)
{
System.out.println("In base f");
}
public void g(String a)
{
System.out.println("In base g");
}
}
public class MoreUseful extends Useful
{
public void f(String a)
{
System.out.println("In derived f");
}
public void g(Object a)
{
System.out.println("In derived g");
}
}
I am trying to override base class method but I am changing the parameters in derived class.
in method MoreUseful.f() I am using subclass parameter (String) as against Object in base class.
in method MoreUseful.g() I am using superclass parameter (Object) as against String in base class.
Is it possible to override these way?
Which of the above two cases will be correct overriding?
No, that's not possible, and would be a violation of the LSP.
By inheriting from a class, you express that your subclass MoreUseful is actually a Useful and therefore exposes all the functionality that Useful exposes. If you removed the ability to invoke f with an object, you'd break that promise.
You are free to overload f so that you have an f(String s) method though.
The g() method is indeed overriden. f(), however, is not overriden - it's overloaded. An easy way to verify this is to add #Override on each method you intend to override - if it results in a compilation error, you aren't overriding properly.

How do I access the super-super class, in Java? [Mini-example inside] [duplicate]

This question already has answers here:
Why is super.super.method(); not allowed in Java?
(22 answers)
Closed 9 years ago.
In the example below, how can I access, from C, the method method() of the class A?
class A {
public void method() { }
}
class B extends A{
public void method() { }
}
class C extends B{
public void method() { }
void test() {
method(); // C.method()
super.method(); // B.method()
C.super.method(); // B.method()
B.super.method(); // ERROR <- What I want to know
}
}
The error I am getting is
No enclosing instance of the type B is
accessible in scope
Answer: No, this is not possible. Java doesn't allow it. Similar question.
You can't - and very deliberately. It would violate encapsulation. You'd be skipping whatever B.method wants to do - possibly validating arguments (assuming there were any), enforcing invariants etc.
How could you expect B to keep a consistent view of its world if any derived class can just skip whatever behaviour it's defined?
If the behaviour B provides isn't appropriate for C, it shouldn't extend it. Don't try to abuse inheritance like this.
Following code could be a work-around (not nice, but should work):
class A {
public void method() { }
}
class B extends A {
public void method() { }
protected void superMethod() {
super.method();
}
}
class C extends B {
public void method() { }
void test() {
method(); // C.method()
super.method(); // B.method()
superMethod(); // A.method()
}
}
Well, there is no direct way of doing this but you can always try workarounds.
I am not sure of the purpose of accessing method in class A from class C but you can always get hold of that method.
You could either create an instance of class A in class C and if that looks too simple, try using reflection API...
[link text][1]
Extreme Java
You shouldn't.
If you want to access the methods in A, extend from A instead of B.
When B extends A, it assumes that the underlying A-object won't be manipulated in other ways than how it does it itself. Therefore, by directly accessing the methods of A, you could be breaking how B functions.
Imagine, for instance, you have a class that implements a list, MyList. Now, imagine we extend this list with another class called MyCountingList, which overrides the add() and remove() methods to count the elements being added/removed. If you bypass the add() method MyCountingList provides, using the one MyList has instead, you've now broken the counting feature of MyCountingList.
So, in short, just don't.

Categories

Resources