Unit 9 - Inheritance
Access Modifiers: Public, Private, Protected
- Public: can be accessed from anywhere inside the program, that is, they can be accessed within the same class as well as from outside the different classes
- Private: they can be accessed only within the same class where they have been declared, they will not be visible to the outside world
- Protected: used to access the methods or data members of a class within the same package as well as outside the package but only through inheritance
- more visibility than private, less than public
public class Cow {
// instance variables
private String cowType;
private String sound;
protected int numMilkings;
public Cow (String cowType, String sound){
this.numMilkings = 0;
this.cowType = cowType;
this.sound = sound;
}
public int getNumMilkings(){
return numMilkings;
}
public void setSound(String sound){
this.sound = sound;
}
public String toString(){
return "Type of Cow: " + cowType + "; " + "Sound: " + sound + "; " + "Number of Milkings: " + numMilkings;
}
public static void main(String[] args) {
Cow firstCow = new Cow("holstein", "moo");
System.out.println(firstCow);
System.out.println("Number of Milkings: " + firstCow.getNumMilkings());
firstCow.setSound("oink!");
System.out.println("Mutated Cow:" + firstCow);
}
}
Cow.main(null);
Subclasses
- Method to create hierarchy between classes by inheriting from other classes
- parent and child classes
- extends extend a class to show its inherited and extends functionality
- Subclass inherits all methods and fields from superclass, and constructor can be carried out from subclass
- super refers to superclass or parent objects
// Hacks 1
private class Plane {
private String model = "Boeing 737";
private int age = 3; //two attributes
public void getAge(String model, int age) {
println("Age: " + age);
}
}
private class Jet extends Plane {
private String color = "blue";
}
//hack 2
public class Plane {
private String model = "Boeing 737";
private int age = 3;
public void engineBurr() {
System.out.println("brrrrrr");
}
}
private class Jettison extends Plane {
public Jettison(String model, int age, String color) {
super(model, age);
this.color = color;
@Override
public void engineBurr() {
System.out.println("BRRRRRRRRR");
}
}
//Hack 3
private class Jets extends Plane {
@Override
public void getAge(String model, int age, String color) {
println("Age: " + age);
}
public void getAge(int age, String color) {
println("Age: " + age);
}
}