I am learning Java and as per knowledge I know that all objects are created at runtime when the function is called.
I came across these two examples which have let me to a confusion
Example 1:
class Animal { void jump() { System.out.println("Animal"); } } class Cat extends Animal { void jump(int a) { System.out.println("Cat"); } } class Rabbit extends Animal { void jump() { System.out.println("Rabbit"); } } public class Circus { public static void main(String args[]) { Animal cat = new Cat(); Rabbit rabbit = new Rabbit(); cat.jump(); rabbit.jump(); } } Output of this Code is:
Animal Rabbit
Example 2
class Employee { String name = "Employee"; void printName() { System.out.println(name); } } class Programmer extends Employee { String name = "Programmer"; void printName() { System.out.println(name); } } public class Office1 { public static void main(String[] args) { Employee emp = new Employee(); Employee programmer = new Programmer(); System.out.println(emp.name); System.out.println(programmer.name); emp.printName(); programmer.printName(); } } O/P of this example is
Employee Employee Employee Programmer
Now my question is why in example 1 cat.jump() is returning output as 'Animal' and in example 2 why programmer.printName() is returning 'Programmer'.
I think this has something to do with dynamic and static binding but I'm not able to understand how it is being implemented in these examples.
(int a)onjumpinCat. This makes it an entirely differentjumpmethod. For more information, you'll want to read some tutorials, such as the trail that starts here.