C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: In main we create a new instance of B but treat it as an A reference. We use a method from A, but the B method is selected.
Call: This method is implemented on both A and B. The most derived B implementation is used when an A reference is acted upon.
Java program that uses derived class
class A {
public void call() {
System.out.println("A.call");
}
}
class B extends A {
public void call() {
System.out.println("B.call");
}
}
public class Program {
public static void main(String[] args) {
// Reference new B class by A type.
A a = new B();
// Invoke B.call from A class instance.
a.call();
}
}
Output
B.call
Dog: On the Dog class we can use the methods from Animal and Dog. So the dog can breathe() and bark().
Note: We find we can instantiate parent classes, or child classes, directly. The best class depends on what your program is doing.
Java program that uses extends
class Animal {
public void breathe() {
System.out.println("Breathe");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Woof");
}
}
public class Program {
public static void main(String[] args) {
// On an animal we can call one method.
Animal animal = new Animal();
animal.breathe();
// On a dog we can use Animal or Dog methods.
Dog dog = new Dog();
dog.breathe();
dog.bark();
}
}
Output
Breathe
Breathe
Woof
Quote: One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes.
Multiple Inheritance: oracle.com