Key Concepts

Review core concepts you need to learn to master this subject

Inheritance in Java

// Parent Class class Animal { // Animal class members } // Child Class class Dog extends Animal { // Dog inherits traits from Animal // additional Dog class members }

Inheritance is an important feature of object-oriented programming in Java. It allows for one class (child class) to inherit the fields and methods of another class (parent class). For instance, we might want a child class Dog to inherent traits from a more general parent class Animal.

When defining a child class in Java, we use the keyword extends to inherit from a parent class.

Inheritance and Polymorphism
Lesson 1 of 1
  1. 1
    When you hear the word “inheritance,” code may not be the first thing that springs to mind; you’re probably more likely to think of inheriting genetic traits, like eye color from your mother or a s…
  2. 2
    So how do we define a child class so that it inherits from a parent class? We use the keyword extends like this: class Shape { // Shape class members } class Triangle extends Shape { // add…
  3. 3
    Hang on, you might be thinking, if the child class inherits its parent’s fields and methods, does it also inherit the constructor? Let’s take a look at how the super() constructor works! Let’s say…
  4. 4
    You may recall that Java class members use private and public access modifiers to determine whether they can be accessed from outside the class. So does a child class inherit its parent’s private m…
  5. 5
    In Java, if Orange is a Fruit through inheritance, you can then use Orange in the same contexts as Fruit like this: String makeJuice(Fruit fruit) { return “Apple juice and “ + fruit.squeeze(); …
  6. 6
    One common use of polymorphism with Java classes is something we mentioned earlier — overriding parent class methods in a child class. Like the + operator, we can give a single method sligh…
  7. 7
    An important facet of polymorphism is the ability to use a child class object where an object of its parent class is expected. One way to do this explicitly is to instantiate a child class object…
  8. 8
    Usually, when we create an array or an ArrayList, the list items all need to be the same type. But polymorphism puts a new spin on what is considered the same type… In fact, we can put instances…
  9. 9
    When we call a method that contains parameters, the arguments we place in our method call must match the parameter type. Similar to the previous exercise, polymorphism gives us a little more flexib…
  10. 10
    Excellent work! You’ve learned quite a bundle about inheritance and polymorphism in Java: - A Java class can inherit fields and methods from another class. - Each Java class requires its own file, …

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo