Java Inheritance
Inheritance:
- A child class will have the variables and methods that a parent class has (except for those marked as "private")
- Create a child class with the "extends" keyword followed by the name of the class that it inherits from
- Inheritance is useful if you want to make many different classes that have some parts in common
- A parent class can mark variables and methods as "protected", in which case they can be accessed within the child class
Overriding a Parent Method:
- An inherited method can be modified to do something different when called from a child class
- This could be useful if you want to inheret only some of the parent methods
Constructor in child class:
- A constructor for a child class must use the 'super' keyword to call the constructor of the parent class
- The 'super' call must be the first line of the function
Arrays of Related Objects:
- An array that stores objects of a class can also store objects of its inherited classes
Challenge
Create a class called "Bird" which stores the weight, height, and wingspan. Make a constructor that fills those values according to parameters. Make the functions "makeSound" and "fly"; "makeSounds" should display "chirp chirp", and the function "fly" should display "flap flap". Then create two child classes "Hawk" and "Sparrow". In the hawk class, add a function called "hunt" which will display "hunting", and change the inherited "makeSound" class to display "*majestic scream*" In the sparrow class, add a function called "findSeeds" which will display "finding seeds". Now in main, create an object (instantiation) of each class and have them both perform their functions.