Constructors and Constructors Overloading - java

Can any one explain?
When we are overloading a constructor with different parameters one having data type object and other having data type string, and when we are creating the object of this class with providing input parameter as null it is calling the constructor with string as input parameter but not the constructor having input parameter as Object. Since Object is the super class of String, can any one tell me why it is calling constructor with input parameter string?
Class A
{
public A(Object o)
{
System.out.println("Object Drawn");
}
public A (String o)
{
System.out.println("String Drawn");
}
public static void main(String args[])
{
new A(null);
}
}
Output:- String Drawn

It always calls the most specific matching method or constructor. If it didn't you would always call Object and overloading it would be pointless.
This approach is using in Java and C++

Related

Unexpected overloaded method compiler selection with null parameter [duplicate]

This question already has answers here:
How to do method overloading for null argument?
(7 answers)
Closed 6 years ago.
I am very surprised why output is very much different from what I am expecting , I have two overloaded methods, one having one String and the other an Object as parameter, while calling this method with null parameter, output is just printing
"String"
and not calling method having object as parameter.
Why does Java selects the method having String as parameter, how java determines which overloaded method to call ?
class TestingClass {
public void test(String s) {
System.out.println("String");
}
public void test(Object o) {
System.out.println("Object");
}
public static void main(String[] args) {
TestingClass q = new TestingClass();
q.test(null);
}
}
There is no overriding in this code, only method overloading. When the compiler has to choose which of the two test methods to execute (since null can be passed to both), it chooses the one with the more specific argument type - test(String s) - String is more specific than Object since it is a sub-class of Object.
The other method can be called using :
q.test((Object) null);
Without adding a possible new answer, let me suggest you to extend your code like following,
public class Overload {
public static void main(String[] args) {
new Overload().test(null);
}
public void test(String s) {
System.out.println("String");
}
public void test(Object o) {
System.out.println("Object");
}
public void test(Integer s) {
System.out.println("Integer");
}
}
Comment out any one of Object or Integer version any see it for yourself. The answer being already provided by others.

Passing null to the Overloaded methods [duplicate]

This question already has answers here:
How to do method overloading for null argument?
(7 answers)
Closed 6 years ago.
I am confused with the Output of the following two programs.
When I'm only having two methods with parameters as String and Object in Program 1 it gives me output as String.
But when I add a new method with parameter as Integer in Program 2 it won't compile and gives error as
The method nullTest(Object) is ambiguous for the type testNull
Program 1 :
package onkartest;
public class TestNull {
public static void nullTest(Object b)
{
System.out.println("object");
}
public static void nullTest(String x)
{
System.out.println("String");
}
public static void main(String x[])
{
nullTest(null);
}
}
Output : String
Program 2 :
package onkartest;
public class TestNull {
public static void nullTest(Object b)
{
System.out.println("object");
}
public static void nullTest(String x)
{
System.out.println("String");
}
public static void nullTest(Integer i)
{
System.out.println("Integer ");
}
public static void main(String x[])
{
nullTest(null);
}
}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method nullTest(Object) is ambiguous for the type testNull
at onkartest.testNull.main(testNull.java:26)
And also if I run the program with keeping only Object parameter method, it gives me output as Object.
Can you explain me the reason behind this behavior?
When determining which function to use, Java will try to find the function with the most specific input parameter. So in the first case, the String function was chosen as null can be assigned to a String. Object is a parent of String so the String function will be more specific.
In the second case, both Integer and String inherits from Object, and both of these can be assigned to null. Therefore, both of them are equally specific and Java cannot decide which one of these functions to use.
The reason is that in case of method overloading,when a parameter is passed that can be referenced by both child and parent class, the method with the parameter of type child class will always be called.
The String is a subclass of Object and therefore its method is called.
In the following example we have class Parent that can be considered as Object class and Child class that can be considered as String class.
Now what happens with your program 1, exactly the same thing happens, that is the method with parameter of child class object gets called
public class Program
{
public static void method(Parent p1)//Consider the Parent as Object
{
System.out.println("parent");
}
public static void method(Child c)//Consider the Child as String
{
System.out.println("Child");
}
public static void main(String []args)
{
method(null);
}
}
class Parent//consider Parent as Object
{
}
class Child extends Parent//consider Child as String
{
}
But suppose now you add the following class Child2 that can be considered as your Integer class. Child2 is a subclass of Parent, just like Integer is a subclass of Object
class Child2 extends Parent
{
}
and add the following method
public static void method(Child2 c)//Consider the Child2 as Integer
{
System.out.println("Child");
}
Now what happens is exactly what happend in your program 2. The reason is that the compiler is not able to decide which is the right one because of the ambiguity because both are child class of the same same parent class and most importantly none of them(Either Child2 or Child) is a parent of the other.
If we had a case where we have either of the 2 classes a subclass of the other and both inherit Parent class, then there would be no ambiguity and the method with child class will be called.
When try to pass the arguments to a method it first try a exact same type. if not then try to have immediate super type. in first program Object is super than string so it match with String. But in second program Object class have two children in same level so java compiler is not able to find which one to be mapped the null value.

Method overloading with dynamic casting

I'm looking into the method overloading of Java.
Take the next sample :
public static void main(String[] args) {
Object object = "some String";
System.out.println(object.getClass().getSimpleName());
System.out.println(belongsToAllowedTypes(object.getClass().cast(object)));
String string = "another String";
System.out.println(belongsToAllowedTypes(string));
}
public static boolean belongsToAllowedTypes(Object value) {
return false;
}
public static boolean belongsToAllowedTypes(String value) {
return true;
}
I'm expecting an output like :
String
True
True
Just because I get the String class and cast the Object to that class before I invoke the method.
But no luck, I'm getting false in the second println.
So it's still processed as an Object (however the class is String)
If I change it to :
System.out.println(belongsToAllowedTypes(String.class.cast(object)));
I do get a True.
Can anyone explain this behavior?
The method to call is determined at compile time. So with object having type Object the type of
object.getClass().cast(object))
at compile time is an Object independent of the dynamic content of object.

What is super pointing to in the following code?

What address is super in 4th line pointing to in the following code?
public class SuperChk {
private void test() {
System.out.println(toString());
System.out.println(super.toString()); //4
}
#Override
public String toString() {
return "Hello world";
}
public static void main(String[] args) {
SuperChk sc1 = new SuperChk();
sc1.test();
}
}
Look at it this way.
Implicitely, your class will inherit from the superclass Object so you can access your object either with an Object reference or with a SuperChk reference
Object
public class Object {
// Other methods
public String toString(){
// This is the method super.toString() will use once called in SuperChk
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
}
SuperChk
public class SuperChk extends Object {
private void test() {
System.out.println(toString());
System.out.println(super.toString()); //4
}
#Override
public String toString() {
return "Hello world";
}
public static void main(String[] args) {
SuperChk sc1 = new SuperChk();
sc1.test();
}
}
Output
Hello world
SuperChk#15db9742
You can see that the toString() method from the Object class prints :
The class name first.
Then "#"
Then the hexadecimal representation of the HashCode which is also defined in a method of the superclass Object
Classes in Java all derive from Object. Since you have no explicit parent class, then the parent is Object and super is referencing Object. Object does support the toString() method. See the Java class hierarchy.
super is not an expression. So super does not "point to" anything, and you cannot use super by itself.
super.something() is an expression that allows you to call a method on the object that this points to, but the lookup for which implementation to call proceeds up from the superclass of the class whose code this is in, rather than up from the object's runtime class as would happen if you did this.something().
Here, both toString() and super.toString() are called on the object that this points to (which is a SuperChk instance). However, they call different toString() implementations -- in the first case, the lookup is based on the runtime class of the object, which is SuperChk, and SuperChk does provide its own implementation of toString(), so SuperChk's implementation is used. In the second case, the lookup is based on the class that is the superclass of the class the code is in (SuperChk), which is Object, so Object's toString() is used.

Method overriding in Java. Why is this program not calling the sub class method?

Why is this program not calling the sub class method? What is the concept behind it? I'm totally confused with this.
Below is the code.
Super class
public class TV {
public void checkType(TV b) {
System.out.println("Its a TV");
}
}
Child class
public class LedTv extends TV {
public void checkType(LedTv b) {
System.out.println("Its a LED TV");
}
}
Test case to get the result
public class TestTV {
public static void main(String argss[]) {
TV a = new TV();
TV b = new LedTv();
a.checkType(a);
b.checkType(b);
}
}
Both of the checkType method prints
Its a TV
Its a TV
public class LedTv extends TV {
#Override //always put this here
public void checkType() {//no need for argument
System.out.println("Its a LED TV");
}
}
As you can see from the above example I added an annotation #Override. While this isn't necessary it forces the compiler to check and make sure you are actually overriding something. If you are not you will get an error, which helps solve bugs. The reason I got rid of the argument that you are passing to check type is because it's redundant. you can always use the this keyword to point to the object you are currently inside of.
I realise I forgot to explain what overriding and overloading is so I think this example will show you.
public class Main{
public static void main(String[] args){
new Main();
}
Main(){
new SuperClass().method();
new SuperClass().method(101010);
new Subclass().method();
new Subclass().method(595959);
}
class SuperClass{
SuperClass(){
System.out.println(this.getClass().getSimpleName());
}
public void method(){
System.out.println("method() from SuperClass -> Calling method(int x)");
method(0);
}
public void method(int x){
System.out.print("method() from SuperClass " + x + "\n\n");
}
}
class Subclass extends SuperClass{
#Override
public void method(int x){
System.out.print("method() from SubClass " + x + "\n\n");
}
}
}
Output
SuperClass
method() from SuperClass -> Calling method(int x)
method() from SuperClass 0
SuperClass
method() from SuperClass 101010
Subclass
method() from SuperClass -> Calling method(int x)
method() from SubClass 0
Subclass
method() from SubClass 595959
As you can see in SuperClass method() is overloaded with an int as method(int x) and method() is overridden in Subclass. In the output you can clearly see whats going on. What's the difference between overloading a method and overriding it in Java?
Methods get overriden during inheritance when they have the same signature. According to the docs signature depends on:
the method name
the number of the arguments
the type of the arguments
In your case these methods
public void checkType(TV b)
public void checkType(LedTv b)
Clearly have different signatures as the type of the argument is different. What you get is called method overloading
overriding method must have the same types for arguments. If you want to override method in subclass it must have the same arguments only return type can be different but from the same hierarchy as in superclass method
void checkType(TV) is a different function prototype to void checkType(LedTv).
Therefore you are not overriding, but rather you are overloading.
For overriding, the function name and parameter types must be identical, and the return type related. The exact definition of relatedness is beyond the scope of this question.
You are doing method overloading. For method overriding both the method signature of the parent and child class should be same. So in the child class instead of this
public void checkType(LedTv b) {
System.out.println("Its a LED TV");
}
type this and check -
public void checkType(TV b) {
System.out.println("Its a LED TV");
}
Because both of your objects are of type TV.
TV a = new TV();
TV b = new LedTV();
is basically the same object base type. In case of creating b, all you do is basically telling you want superclass instance with the sub-class functionality as well. And you are overloading the methods, not overriding them. You tell the program if parameter is LedTV, print out this, if parameter is TV, print out this. You are outsourcing the if-else logic to the program itself, simply. What you do is
if(TV == TV) print TV
else if (TV == LedTV) print LedTV
But the problem is both objects are of type TV in your code, so the superclass method is always used and the first if is true, and second one is not even evaluated.
Change b to this:
LedTv b = new LedTv();
b.checkType(b);
It will now work correctly, because b is of type LedTV..

Categories