Created
September 18, 2021 22:40
-
-
Save evrentan/033bee53694f28c5515f8a2b7825c92f to your computer and use it in GitHub Desktop.
Java Inheritance Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//superclass | |
class Animal { | |
public void eat() { | |
System.out.println("Animal can eat"); | |
} | |
} | |
// subclass, Dog class inherits Animal class | |
class Dog extends Animal { | |
// overrides the eat() method of the Animal superclass | |
@Override | |
public void eat() { | |
// call eat() method in the superclass | |
super.eat(); | |
System.out.println("Dogs eat special dog food"); | |
} | |
// a new method in the subclass | |
public void bark() { | |
System.out.println("Dogs bark"); | |
} | |
} | |
class Main { | |
public static void main(String[] args) { | |
Dog newDog = new Dog(); | |
newDog.eat(); | |
newDog.bark(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment