Loading topic
Dog and a Cat both eat and sleep. Writing the same code twice is tedious and easy to get wrong. Java solves this with inheritance. In this chapter you will learn what inheritance is and how to write your first subclass with the extends keyword.6 min readextends. This chapter explains what the subclass actually gets from its superclass. You will learn which members a subclass inherits and which ones it can't use by name. You will also learn why a private field can be part of an object even though the s6 min readDog is an Animal, but "Some sound" is a poor description of what a dog says.6 min readsuper keyword lets a subclass reach the superclass version of a method or field.6 min readsuper(...). This chapter covers the order in which Java runs everything when you write new Dog(). That order explains some confusing bugs.6 min readclass Dog extends Animal. You saw that Dog inherits from Animal. This chapter goes one level higher. Every Java class has a parent at the very top, and that parent is a class named Object.6 min read@Override annotation. @Override asks the compiler to check your work. It is one of the cheapest ways to avoid a whole class of 6 min readextends, how to override a method, and how @Override works. You will learn to tell three look-alike features apart: overriding, overloading, and hiding. Beginners often mix them up. The mix-up causes bugs that compile cleanly and then pr5 min readabstract and final.5 min readclass Dog extends Animal. Java has a second way to relate types: an interface. This chapter explains what an interface is and how implements differs from extends. It also covers why a class can have only one superclass but many interfaces. This chapter assumes you5 min readextends, override methods, and call super. The next question is when to use these tools. Inheritance is one way to reuse code. It is not always the best way.6 min read