/* This program demonstrates the structure of a user defined class, attributes and methods, constructors, accessor and mutator methods, creating objects of a class, and calling instance methods. */ // The following line implies that the class Boat has been placed inside a folder called Vehicle. // It can be now imported and used by any program in the same folder the CONTAINS the folder Vehicle. package Vehicle; public class Boat // Class has to be public to make it usable by other classes. { // Attributes of a class. By default, they are private and not accessible outside the class String name; int length; boolean hasSails; double engine; boolean floorIt; /* Constructors are methods that are called automatically when a class is instantiated (an object is created). They are always public, and have no return type. The name matches the class name. This is also an example of polymorphism (method overloading). The default constructor is called when no parameters are passed. */ public Boat() { // If no values are provided, the boat is automatically the Flying Dutchman name="Flying Dutchman"; length = 100; hasSails = true; engine = 9001; floorIt = true; } // The parameterized constructor is called when the user passes in the appropriate number of parameters. // We can have many of these. public Boat(String n, int l, boolean hS, double e, boolean fI) { name=n; length = l; hasSails = hS; engine = e; floorIt = fI; } /* Accessor and mutator methods. They are always public. Accessors begin with "get", and take no parameters. The return type should match the type of the attribute. Mutators begin with "set", takes in one parameter of the same type as the attribute, with return type "void". */ public String getName() { return name; } public int getLength() { return length; } public boolean getHasSails() { return hasSails; } public double getEngine() { return engine; } public boolean getFloorIt() { return floorIt; } public void setName(String n) { name = n; } public void setLength( int l) { length = l; } public void setHasSails( boolean hs) { hasSails = hs; } public void setEngine ( double e) { engine = e; } public void setFloorIt ( boolean fi) { floorIt = fi; } // a print method public void print() { System.out.println("Name: "+name+"\nLength: "+length+"\nHas Sails?: "+hasSails+"\nEngine: "+engine+"\nFloor It?: "+floorIt); } public static void main(String [] args) { // We need to create objects of class Boat, before using the methods. Boat fd = new Boat(); // default constructor is called here Boat myBoat = new Boat ("BoatMobile", 50, false, 50000, true); // parameterized constructor is called here. System.out.println(fd.getName()); System.out.println(myBoat.getName()); myBoat.setName("Titanic"); // using the mutator method to change "BoatMobile" to "Titanic" System.out.println(myBoat.getName()); fd.print(); } }