Lecture 8 Inheritance CS 140 Dick Steflik Inheritance

  • Slides: 7
Download presentation
Lecture 8 Inheritance CS 140 Dick Steflik

Lecture 8 Inheritance CS 140 Dick Steflik

Inheritance • A class derived from another class is called a subclass – also

Inheritance • A class derived from another class is called a subclass – also a a derived or child class • The class that a subclass is derived from is called the super class – also the parent class • All classes are derived from class Object – class Object has no super class

Java Class Hierarchy All Java objects are derived from class Object

Java Class Hierarchy All Java objects are derived from class Object

An example public class Airplane{ public int speed, altitude, heading; public Airplane( int s,

An example public class Airplane{ public int speed, altitude, heading; public Airplane( int s, int a, int h){ speed = s; altitude = a; heading = h; } public set. Speed(int new. Speed) { speed = new. Speed; } public set. Altitude(int new. Altitude) { altitude = new. Altitude; } public set. Heading(int new. Heading) { heading = new. Heading; } public faster( int increment) { speed += increment; } public slower(int increment) { speed -= increment; } }

a subclass of Airplane public class Fighter extends Airplane { public int ammo, missiles;

a subclass of Airplane public class Fighter extends Airplane { public int ammo, missiles; public Fighter ( int init. Bullets, int init. Missiles, init. Speed, int init. Altit, int init. Heading) { // let the super class initial its fields super( init. Speed, init. Heading); ammo = init. Bullets; missiles = init. Missiles; } public void launch. Missile() { missile-- ; } public void fire. Burst( int count) { ammo -= count)

using the classes Fighter F 18 = new F 18(1000, 6, 0, 0, 0)

using the classes Fighter F 18 = new F 18(1000, 6, 0, 0, 0) F 18. set. Speed = 100; while ( F 18. get. Speed() < MACH 1) { F 18. faster(10); F 18. climb(10); }

Inherited public fields can be used directly Inherited public methods can be used directly

Inherited public fields can be used directly Inherited public methods can be used directly you can declare new fields in the subclass that are not in the superclass the constructor of the subclass can use the constructor of the super class you can define new methods in the subclass that are not in the superclass the subclass can have an instance method with the same signature as one in the superclass thus overriding it • you can write a new static method in the subclass that has the same signature as on in the super class thus hiding it • private fields and methods are not inherited • • •