70 likes | 189 Views
Lecture 8 Inheritance. CS140 Dick Steflik. 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
E N D
Lecture 8Inheritance CS140 Dick Steflik
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
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 setSpeed(int newSpeed) { speed = newSpeed; } public setAltitude(int newAltitude) { altitude = newAltitude; } public setHeading(int newHeading) { heading = newHeading; } 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; public Fighter ( int initBullets, int initMissiles, initSpeed, int initAltit, int initHeading) { // let the super class initial its fields super( initSpeed, initSpeed, initHeading); ammo = initBullets; missiles = initMissiles; } public void launchMissile() { missile-- ;} public void fireBurst( int count) { ammo -= count)
using the classes Fighter F18 = new F18(1000, 6, 0, 0, 0) F18.setSpeed = 100; while ( F18.getSpeed() < MACH1) { F18.faster(10); F18.climb(10); }
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