Super

Ok so for a while I was struggling to figure out what super was in terms of constructors and how to use it, even with the Stackoverflow post because the top voted example seems to be pretty thin. Basically it seems like we use super to pass in arguments FROM a subclass and then add on any specific fields that we need to.

If we have a field that we want to set/update that is part of the superclass, then we would use a setter in that instance rather than trying to use a field/variable of the same name as I was trying to do before.


// VEHICLE CLASS

public class Vehicle {
	
	private String type;
	private String name;
	private int topSpeed;
	private int wheels;
	
	public Vehicle() {
		
		this.type = "Unknown";
		this.name = "Unknown";
		this.topSpeed = 9999;
		this.wheels = 0;
	}
	
	public Vehicle(String type, String name, int topSpeed, int wheels) {
		
		this.type = type;
		this.name = name;
		this.topSpeed = topSpeed;
		this.wheels = wheels;
	}
	
	public void getName() {
		
		System.out.println("The name is " + name);
	}
	
	public void stop() {
		
		System.out.println("Stopping");
		System.out.println("Current speed is 0");
	}
	
}


// CAR CLASS


public class Car extends Vehicle{
	
	private int gears;
	private int doors;

	// Create a generic vehicle, but add on gears and doors
	public Car() {
		
		// super(type, name, topSpeed, wheels);
		this.gears = 10;
		this.doors = 2;
	}
	
	// Create a generic vehicle but replace type, name, topSpeed, wheels, and add gears and doors
	// We use super to pass in arguments FROM the subclass, not to neccessarily INVOKE the superclass
	public Car(String type, String name, int topSpeed, int wheels, int gears, int doors) {

		super(type, name, topSpeed, wheels);
		this.gears = gears;
		this.doors = doors;
		
	}
	
	public void getGears() {
		
		System.out.println("Gears: " + gears);
	}
	
	
	
	
}


// ENEMY CLASS

public class Enemy {
	
	private int health;
	private String weapon;
	private String armor;
	private String type;
	private String name;
	
	public Enemy() {
		
		this.health = 100;
		this.weapon = "Sword";
		this.armor = "Leather";
		this.type = "Warrior";
		this.name = "Bob";
	}
	
	public void setWeapon(String weapon) {
		
		this.weapon = weapon;
	}
	
	public void showWeapon() {
		
		System.out.println("The " + type + " has a " + weapon);
	}
	
	
}

// ORC CLASS

public class Orc extends Enemy {
	
	
		int damageBonus;
	
		public Orc() {
		
			this.damageBonus = 20;
			setWeapon("Mace");
	}
	
	
}

Written on June 21, 2017