Below is the code which I am trying to analyze.
class Acc{
public void aMethod(List<Integer> A){
System.out.println(A.toString());
}
}
class Back extends Acc{
public void aMethod(String A){
System.out.println(A);
}
}
Here if I invoke it as
Acc a = new Back();
a.aMethod(list);
But upon debugging the method of parent class is being called.But it should dynamically call method of Back as per my understanding.Please help me understand of this behaviour.Now again If I keep parent class argument as List<Integer> and child one as List<String> then it gives a name clash thing.Why not in this case?
Parent class method public void aMethod(List<Integer> A) and child class method is public void aMethod(String A).
Both have different parameters, so it is not Method Overriding. However in child class it can be thought of as Method Overloading.
When you call the method, you are passing the list parameter and there is only only method that matches this signature and that is of parent class. So the method of parent class gets called.
Method Overriding
For method overriding methods in base class and child class must have same signature i.e. same name and same arguments. However method in child class can have higher scope access specifier than base class's method.
In simpler words, if method in base class is default then method in child class can be public.
Here are some rules for method overriding:
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
If you check this and then code written, it would be clear where its wrong.
Related
This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Java cast to superclass and call overload method
(1 answer)
Closed 5 years ago.
Super keyword related doubt.
class Parent{
int x=40;
void show()
{
System.out.println("Parent");
}
}
class Child extends Parent
{ int x=20;
void show() //method overriding has been done
{
System.out.println(super.x); // prints parent data member
System.out.println(((Parent)this).x); /*same output as previous statement which means super is similar to (Parent)this*/
System.out.println("child");
super.show(); // invokes parent show() method
((Parent)this).show(); //Doesnt invoke parent show() method.Why?
}
public static void main(String s[])
{
Child c1=new Child(); //Child class object
c1.show();
}}
So, System.out.println(super.x) and System.out.println(((Parent)this).x) prints the same value.So if super.show() calls parent class show() method then why is ((Parent)this).show(); unable to call parent show()? Please tell appropriate explaination for this.
Constructor Chaining
in Java keyword this represent current object and when one class extends another then its super class reference variable may hold child class reference variable that's is in your code is ((Parent)this).x ,
while super keyword is used to call directly super class constructor and its variables.
at the same time when super class variables holds child class object and when we use super it refers same object .
How to call one constructor from another constructor in Java or What
is Constructor Chaining in Java is one of the tricky questions in Java
interviews. Well, you can use this keyword to call one constructor
from another constructor of the same class if you want to call a
constructor from based class or super class then you can use super
keyword. Calling one constructor from other is called Constructor
chaining in Java. Constructors can call each other automatically or
explicitly using this() and super() keywords. this() denotes a
no-argument constructor of the same class and super() denotes a no
argument or default constructor of parent class. Also having multiple
constructors in the same class is known as constructor overloading in
Java.
Read more: http://www.java67.com/2012/12/how-constructor-chaining-works-in-java.html#ixzz4bJ5C069o
Calling ((Parent) this).show(); on what is really a Child object causes Child.show() to be called. Whether you are doing it as myObject.show() or through this makes no difference for which version of the method gets called — it’s always the method determined by the object’s runtime type, in this case Child.
So you have a recursive call, leading to infinite recursion.
super.show() on the other hand calls the method in the super class, in this case Parent.
I have an abstract class and its concrete subclass, when I create an object of subclass it automatically calls the super constructor. Is the JVM internally creating an object of the abstract class?
public abstract class MyAbstractClass {
public MyAbstractClass() {
System.out.println("abstract default constructor");
}
}
public class ConcreteClass extends MyAbstractClass{
public static void main(String[] args) {
new ConcreteClass();
}
}
then how constructor exists without an object in JVM ?? (In case of abstract class)
Also constructor gets executed after object is being created then without creating the object of abstract class how the default constructor get executed ?? (This is mentioned in Java Doc)
Is it true that you can't instantiate abstract class?
Yes.
Is JVM internally create object of abstract class ?
No, but it's a common misunderstanding (and that wouldn't be an unreasonable way for it to be done; prototypical languages like JavaScript do it that way).
The JVM creates one object, which is of the class you created (in your case, ConcreteClass). There are aspects of that one object that it gets from its superclass (MyAbstractClass) and from its subclass (ConcreteClass), but there is only one object.
The object is an aggregate of all of its parts, including parts that seem to have the same name, such as a method of the superclass that is overridden by the subclass. In fact, those methods have different fully-qualified names and don't conflict with one another, which is why it's possible to call the superclass's version of an overridden method.
So if it's just one object, why do you see the call to MyAbstractClass's constructor? Before we answer that, I need to mention a couple of things the Java compiler is doing that you don't see in the source code:
It's creating a default constructor for ConcreteClass.
In that constructor, it's calling the MyAbstractClass constructor.
Just to be thorough: In the MyAbstractClass constructor, it's adding a call to the superclass's (Object) constructor, because there's no super(...) call written within the MyAbstractClass constructor.
Here's what the code looks like with the bits the Java compiler adds for you filled in:
public abstract class MyAbstractClass {
public MyAbstractClass() {
super(); // <== The Java compiler adds this call to Object's constructor (#3 in the list above)
System.out.println("abstract default constructor");
}
}
public class ConcreteClass extends MyAbstractClass{
ConcreteClass() { // <== The Java compiler adds this default constuctor (#1 in the list above)
super(); // <== Which calls the superclass's (MyAbstractClass's) constructor (#2 in the list above)
}
public static void main(String[] args) {
new ConcreteClass();
}
}
Okay, with that out of the way, lets touch on a point TheLostMind very usefully mentioned in a comment: Constructors don't create objects, they initialize them. The JVM creates the object, and then runs as many constructors (they really should be called initializers) against that one object as necessary to give each superclass a chance to initialize its part of the object.
So in that code, what happens (and you can step through this in a debugger to fully understand it) is:
The JVM creates an object
The ConcreteClass constructor is called
The first thing that constructor does is call its superclass's constructor, in this case MyAbstractClass's constructor. (Note that this is an absolute requirement: The Java compiler will not allow you to have any logic in the constructor itself prior to the superclass constructor call.)
The first thing that constructor does is call its superclass's constructor (Object's)
When the Object constructor returns, the remainder of the MyAbstractClass constructor runs
When the MyAbtractClass constructor returns, the remainder of the ConcreteClass constructor runs
The object is returned as the result of the new ConcreteClass() expression.
Note that the above would get more complicated if there were instance fields with initializers. See the JLS and JVM specs for the full details.
JVM doesn't create object of abstract class. it is calling its super constructor
JVM will create one object, an instance of the concrete class which inherits fields and methods of abstract class
I have derived a class in java.
I noticed that the superclass constructor gets called before code in my derived class constructor is executed.
Is there a way to invert that order?
Example:
class Animal
{
public Animal()
{
//do stuff
}
}
class Cat extends Animal
{
int var;
public Cat(int v)
{
var = v;
super();
}
}
This is what I would like to do, but calling super() like that gives an error...
No, there is no way to invert that order. If you explicitly call a parent class constructor you are required to do it at the top of your constructor. Calling it later would allow a child class to access the parent class's data before it's been constructed.
No, you can't invert the order of constructor calls this way. A call to super() must be the first statement in a constructor. And if there is no such call, Java inserts an implicit call to super() as the first statement.
The JLS, Section 8.8.7, states:
The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).
ConstructorBody:
{ [ExplicitConstructorInvocation] [BlockStatements] }
There isn't a way to call run the sub class constructor before superclass constructor. That's basically like trying to create the subclass even before the superclass gets created, which is impossible since the subclass relies on superclass attributes to get created.
If I had a method signature
public void myMethod(SuperClass s){
}
and SuperClass has three subclasses, is there any way within myMethod I can get the class name of the subclass which was passed in?
Not sure if it's important, but SuperClass is abstract.
is there any way within myMethod I can get the class name of the subclass which was passed in?
Yes, by using the getClass method:
public void myMethod(SuperClass s){
System.out.println(s.getClass());
}
Remark 1:
This does however sound to me like a Bad Design™.
Whatever you want to do in myMethod consider having a method for it in SuperClass (provide a meaningful default implementation, or make it abstract to force subclasses to implement the method) and call this method on s in your method:
public void myMethod(SuperClass s){
s.abstractMethod();
}
Remark 2:
If myMethods logic is seemingly unrelated to the purpose of the SuperClass and you don't want to put the myMethod code inside this class, consider implementing the visitor pattern instead.
Suppose i have two methods in a class say
public void eat(int i,String s) and
public void eat(String s, int i)
then what is it like. Overloading or overriding?
Overloading means two methods or more with the same name but with different parameters just like your example.While Overriding you implement a method from an interface or abstract class so the method in the super class has an implementation and in the subclass has a different one, Still they have the same method name and parameters.
That would be method overloading, as it meets the conditions for method overloading:
Must have different argument lists
May have different return types, if
argument lists are also different
May have different access modifiers
May throw different exceptions
Also overriding can happen only when inheritance is involved. Since both of your methods are in the same class it cannot be overriding.
This is overloading. Overriding is used in inheritance when you give different implementation to the same method signature.
That's overloading. In brief:
Overriding = replacing
Overloading = give more options
Method Overloading simply means providing two separate methods in a class with the same name but different arguments while method return type may or may not be different which allows us to reuse the same method name.
Method Overriding means defining a method in the child class which is already defined in the parent class with same method signature i.e same name, arguments and return type.
Difference Between Method Overloading and Method Overriding
For more details, you can read Everything About Method Overloading Vs Method Overriding.
Kind of rules about overloading and overriding:
Constructors can be overloaded but not overridden.
Abstract methods must be overridden by the first concrete sub-class.
The overriding method:
must have same argument list,
must have same return type (it can also be a subclass of parent's class' return type,
must not have a more restrictive access modifier,
may have a less restrictive access modifier,
must not throw new or broader checked exceptions,
may throw fewer or narrower checked exceptions, or any unchecked exception.
final methods cannot be overridden.
Only inherited methods may be overridden, and remember that private methods are not inherited.
In a subclass use: super.overriddenMethodName() to call superclass' overridden method.
Overloaded methods:
must have different argument lists,
may have different return types, if argument lists are also different,
may have different access modifiers,
may throw different exceptions.
Methods from a superclass can be overloaded in a subclass.
Polymorphism applies to overriding but not to overloading.
Object type (not the reference variable's type) determines which overridden method is used at runtime.
Reference type determines which overloaded method will be used at compile time.
*Taken from Sun Certified Programmer for Java 6 Study Guide by Kathy Seirra, Bert Bates.
Overloading : In Java Overloading is a Process where a class Contains multiple implementation of methods or constructor by differentiating there no of arguments or types of arguments.
public class TestDemo
{
public void disp(String c)
{
System.out.println(c);
}
public void disp(String c, int n)
{
System.out.println(c+" "+n);
} }
class Sample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
TestDemo obj=new TestDemo();
obj.disp("a");
obj.disp("a",2);
}}
Overriding : Here Methods can be over riding. It must be happen within two class. One is parent & another is child. In this parent class’s method with same name and signature.
public class TestDemo
{
public void eat()
{
System.out.println("Human is Eating");
}
}
class Overriding extends TestDemo
{
public void eat()
{
System.out.println("Human is Eating");
}
public static void main(String[] args)
{
Overriding obj=new Overriding();
obj.eat();
}
}
for more knowledge click on this link : https://arzatechs.com/overloading-and-overriding-in-java/
OVERLOADING:
Two or more methods with same name but different parameters in same class. The same as your question situation.
public void eat(int i,String s)
public void eat(String s, int i)
So, in your case it is method Overloading.
OVERRIDING:
Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class.
ex.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
In this specific case, it's overloading.
Let's differentiate both terms a bit dipper:
Overloading (same function name but different signature):
Two or more methods having the same name with different arguments in
same class.
Overloading is used when you want to extend class functionality.
Overloading is is a compile time polymorphism.
Overriding (same function with the same signature):
Two or more methods having the same method name and same arguments in parent class and child class.
Overriding is used when you want to reuse the existing functionality.
Overriding is a run time polymorphism.
Visit to learn more about overloading and overriding.
Property ------------------- OverLoading -------------------- Overriding
Method Names -------------->must be Same--------------------> must be same
Arg Types------------------>must be Different(atleast arg)---->must be same(Including Order)
Method Signature----------->must be Different(atleast arg)---->must be same(Including Order)
Return Type---------------->No restriction------------------->No restriction
Private,Static,Final------->No Restriction-------------------->Must be Same
Access Modifyer------------>No Restriction--------------------Same
try/Catch----------------->No Restriction--------------------Exception Is thrown
Method Resolution-------->Compiler time (Reference)--------(JVM) Run Time Poymorphism