МОДУЛЬ 8 · УРОК 1
Inheritance: extends
Inheritance allows one class to acquire fields and methods of another. The IS-A relationship is the foundation of code reuse.
30 minBeginnerJavaOOP
What is Inheritance
Inheritance allows a subclass to inherit from a superclass. The IS-A test: Dog IS-A Animal.
public class Animal {
String name;
void eat() { System.out.println(name + " eats"); }
}
public class Dog extends Animal {
void bark() { System.out.println(name + " barks"); }
}
public class Cat extends Animal {
void meow() { System.out.println(name + " meows"); }
}
Dog d = new Dog(); d.name = "Rex"; d.eat(); d.bark();
Cat c = new Cat(); c.name = "Kitty"; c.eat(); c.meow();
What is Inherited
- public and protected fields/methods
- package-private if same package
NOT inherited: private members, constructors, static methods.
Transitivity
C extends B extends A. C inherits from both B and A.
class A { void a() {} }
class B extends A { void b() {} }
class C extends B { } // has a() and b()
✅ Итоги урока
- extends establishes parent-child relationship.
- IS-A is the key test (Dog IS-A Animal).
- Inherits: public, protected, package-private (same package).
- Does NOT inherit: private, constructors, static.
- Inheritance is transitive (C extends B extends A).
- Use only for genuine IS-A relationships.
Next lesson: super and method overriding.
Test: Test: Inheritance
3 вопроса