-1

All classes in Java by default extends Object

public class Dog{
    public Dog()
}
public static void main(String args[]){
    Dog dog = new Dog();
}

If I compile this code JVM will create 2 classes on heap 1- Object 2- Dog. What happens if Dog class implements an Interface and extends an Abstract class?

public interface Animal{
}
public abstract class Mammal{
}

In this case Dog will implement Animal interface and extend Mammal abstract class:

public class Dog extends Mammal implements Animal{
    public Dog();
}

When I create a Dog object now like I did before how many objects is the JVM going to create on the heap?

public static void main(String args[]){
    Animal Dog = new Dog();
}

And if I create Dog with Animal type, what changes?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
dxn
  • 1
  • 3
    When you create a new `Dog`, there are no separate instances of class `Object` and class `Dog`. There is just one object. No matter how many interfaces class `Dog` implements or what class it extends, it will still be one single object. – Jesper May 01 '21 at 18:37

3 Answers3

1

You still have just one Dog instance, regardless of the interfaces it implements or the classes it extends.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Irrespective of how many interfaces your class has implemented, the number of instances created in this case is just one. Whenever you are in doubt, you should think about whether you can instantiate an interface or an abstract class and you will get, NO as the answer. Thus, there will be only as many instances created as you create using the concrete class which is, Dog in this case.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Answer to your last question : we call this polymorphism

if you have same attribute for both of them it will use which belongs to Dog class

Barney Stinson
  • 212
  • 3
  • 12