using an idea called a Class • Classes are an extension of Types • The types we looked at last time are called Primitive Types • Classes are known as Composite Types
the “definition” for some type of Object • When you actually want to use an Object that is of some Class type, you instantiate an instance of that class.
or manipulated like regular variables • We usually affect change in an Object by using methods instead • We restrict access to fields using Access Qualifiers: • Public, Private, Protected
fields private double speed; private double fuel; private boolean isDamaged; // public instance field public String name; // Class field public static int fleetNumber;
Instance of RocketShip // accessing public instance fields System.out.println(spaceShuttle.name); // accessing public Class fields System.out.println(“This shuttle is part of fleet number “ + RocketShip.fleetNumber);
• We want to “protect” data • Instead of setting “gallonsOfFuel” directly, we will call a method “refuel()” that makes sure the value isn’t set without actually putting fuel in
methods and fields from their parent classes • Inherited methods can be overloaded (rewritten) to be specific to the subclass. But the method can still have the same name and Java will magically know which version of the method to use!
the high level instead of at the low level (Objects and Methods) • Inheritance • Design program to leverage inheritance so you don’t repeat yourself • Encapsulation • Group data in to Classes, protect data with access qualifiers and methods • Polymorphism • Method overloading, etc.
our rocket has left in it, but not add to it unless we have actually fueled it up • We create an “accessor” method, called getFuel(), that returns how much fuel is remaining. • getFuel() is public, but the fuel field is private
the rocket ship back to Earth • MartianRocketShip subclasses RocketShip, and so it inherits goHome(). But a MartianRocketShip goes back to Mars. • MartianRocketShip is a RocketShip and a MartianRocketShip but Java knows to use the goHome() that goes to Mars. This is polymorphism.
Variables have “scope”; they are alive as long as their block is alive (block -> curly braces) • Fields are alive as long as their class is alive because that is where they are declared
or setters to use an argument name the same as the field name • Argument is only alive for the duration of the method execution • Use “this” to differentiate between the field and the argument