Unit 9 - inheritance
Notes, Hacks, and HW for inheritance.
What is inheritance?
basically being able to reuse code over and over, defining functions that will be used for all child classes
- each type of the parent c lass will extend, inheriting the base class
SuperClass/SubClass
- protected keyword to keep attiribute from being affected by outside modifiers
- can add own attribute or customize an attribute in the subclass
- can call superclass constructor first
HACK 1
public class Animal {
private String name;
private int numLegs;
public Animal(String name, int numLegs) {
this.name = name;
this.numLegs = numLegs;
}
public String getName() {
return this.name;
}
public int getNumLegs() {
return this.numLegs;
}
}
public class Mammal extends Animal {
private boolean hasFur;
public Mammal(String name, int numLegs, boolean hasFur) {
super(name, numLegs);
this.hasFur = hasFur;
}
public boolean hasFur() {
return this.hasFur;
}
}
public class Animal {
private String name;
private int numLegs;
public Animal(String name, int numLegs) {
this.name = name;
this.numLegs = numLegs;
}
public String getName() {
return this.name;
}
public int getNumLegs() {
return this.numLegs;
}
public void makeNoise() {
System.out.println("bahahaha");
}
}
public class Mammal extends Animal {
private boolean hasFur;
public Mammal(String name, int numLegs, boolean hasFur) {
super(name, numLegs);
this.hasFur = hasFur;
}
public boolean hasFur() {
return this.hasFur;
}
@Override
public void makeNoise() {
System.out.println("rawr");
}
}