340 likes | 444 Vues
Topic 8. Classes, Objects, and Methods. Class and Method Definitions Information Hiding and Encapsulation Objects and Reference. OO revision. Objects A capsule that contains 2 important parts State (attributes or data) What does the object know? Behaviour (methods or functions)
E N D
Topic 8 Classes, Objects, and Methods Class and Method Definitions Information Hiding and Encapsulation Objects and Reference
OO revision • Objects • A capsule that contains 2 important parts • State (attributes or data) • What does the object know? • Behaviour (methods or functions) • What does the object know how to do? • E.g. Cars, employee records, etc. • Class • is the definition of a kind of object (template for creating objects). • E.g. a general description of what an automobile is and what it can do • Encapsulates values & operations on those values. • Also used to group related methods, like the Math class. • Instantiate • An object that satisfies the class definition is said to instantiate the class.
Class Definition Class Name:Car Data: amount of fuel speed license plate Methods (actions): increase speed: How: Press on accelerator pedal stop: How: Press on brake pedal
General class syntax: modifier(s) class ClassIdentifier { classMembers } • Modifier(s) • Used to alter the behaviour of the class • public, private, static • ClassMembers • Named constants, variable declarations and/or methods • Can also be declared as public, private or static
class Car { double fuelAmount = 0.0; double speed = 0.0; String licencePlate = “ “; }
Instantiations of the Class Car First Instantiation Object name: patsCar Second Instantiation Object name: suesCar amount of fuel: 10 litres speed: 55 km / hr licence plate: “135 XJK” amount of fuel: 14 litres speed: 0 km /hr licence plate: “SUES CAR” Third Instantiation Object name: ronsCar amount of fuel: 2 litres speed: 75 km / hr licence plate: “351 WLF”
Car Example • Car Class • Says Car objects has 3 pieces of data (i.e. specifies what kind of data they have. • (litres of fuel in tank; how fast car is moving; license plate) • Class definition has no data individual objects have the data. • Also specifies what actions (methods) the objects can take & how they accomplish those actions. • increaseSpeed • stop • All objects of the Car class have the exact same methods.
Car Example continued….. • Car Object • Instantiates the Car class. • Each object has a name these are variables of typeCar. • patsCar, suesCar, ronsCar
Types of methods • Every method belongs to a class. • Method definitions given inside the definition of the class. • Single value methods • Used to return Java values • Void-methods • Performs some action rather than return a value. • Used to produce Java statements. • E.g. print a message or read in a value from the keyboard) and do not return a value
Single-value Method Definitions: public Type_Returned Method_Name(parameters) { list of statements must contain a return statement } public double getFuelAt() { return fuelAmount; }
void Method Definitions: public void Method_Name(parameters) HEADING { list of statements BODY } public void writeOutput() { System.out.println(“License: “ + licence); System.out.println(“Fuel: “ + fuelAmount); System.out.println(“Speed: “ + speed); return; Can be left out }
PARAMETERS • Formal parameters • Used in the method definition • Actual parameters • Value of the variable that is passed to the method when that method is called/invoked.
Method invocation / Call a method Object_name.method_name(); • Method defined in a class is usually invoked using an object of that class object calling a method
CONSTRUCTORS: • Special type of method . • Not void • Does not return a value • One or more found in every class. • Has the same name as the class & it executes automatically when an object of that class is created. • Used to guarantee that the instance variables of the class are initialised to specific values. • Types of constructors • With parameters • Without parameters (known as the default constructor)
Instantiating / Constructing Objects • To instantiate an object, use the keyword new followed by the class’s constructor method (creates a new instance of a class). • Car patsCar; // creates a new Car variable c = new Car(); // invokes the constructor method or Car patsCar = new Car();
The Member Access Separator • Once you’ve constructed a car, you want to do something with it. • To access the fields or methods of the car you use the . (dot) separator. • Selects a specific member of a Car object by name. • Car patsCar = new Car(); patsCar.fuelAmount = 10.0; patsCar.speed = 55.0; patsCar.licencePlate = “135XJK “; System.out.println(c.licencePlate + “ is moving at “ + patsCar.speed + “ kms/hr”);
Class file REMINDERS • Each Java class definition should be a separate file • Use the same name for the class and the file, except add ".java" to the file name • For now put all the classes you need to run a program in the same directory
Standard methods for a class • Constructor methods • Methods which initialise the object when it is first created. • Reader / Get methods • Methods which allow outside codes to view or get copies of the object’s state. • Writer / Set methods • Methods which allow outside codes to assign new values for the object’s state. • Mutator methods • Methods which allow outside codes to modify the state of an object. • Query methods • Methods which test the state of an object.
class Car { double fuelAmount = 0.0; double speed = 0.0; String licencePlate = “ “; void setMaxSpeed() { speed = 200.0; } }
SIMPLE CLASS EXERCISE!!! • Consider a simple class of objects which represent Rectangles. A brief (& shallow) analysis will reveal the state & behaviour of our simple Rectangle objects. • The state (knows its?) • length (integer) • width (integer) • The behaviour (knows how to?) • Initialise itself • Set its length • Set its width • Return its width • Return its length • Calculate its area • Calculate its perimeter
// File: Rectangle.java // A class which specifies simple Rectangle objects // Note that NONE of the members of Rectangle class // are labelled 'static' class Rectangle { // State (data variables) private int length; private int width;
// Behaviour (instance methods) // Constructor public Rectangle() { length = 0; width = 0; }
// Writer or Set methods public void setLength( int len ) { length = len; } public void setWidth( int wid ) { width = wid; }
// Reader or Accessor methods public int getLength() { return length; } public int getWidth() { return width; }
// Other services public int area() { int the_area = length * width; return the_area; } public int perimeter() { int perim; perim = 2 * (length + width); return perim; }
public boolean isLegal() { if( length >= 0 && width >= 0 ) return true; else return false; } }// end class
Constructor Methods • Must have same name as the class. • Does not have any return type • Not even void • Creates a new instance of the class. • Initialises all the variables & does any work necessary to prepare the class to be used. • If no constructor is exists, Java provides a generic one that takes no arguments. • Better to write your own constructor.
Can have several constructor methods. • Each constructor method must have a different header • Parameter list • Also known as overloading methods. // another constructor public Rectangle(int len, int wid) { length = len; width = wid; }
Access Control • public • Variable or method is available to other programs. • private • To protect variable from external modification • No other code outside this class can directly access these variables or methods. • i.e. If you want objects in the same class to be able to get or set the value of a field or invoke a method. • protected • If you want access restricted to subclasses & members of the same package.
Instance / Non-static Methods • None of the methods in the Rectangle class are labelled static. • These types of methods are designed to be accessed via objects.
NB!! NB!! NB!! • The Rectangle source file must be compiled. • Note that the Rectangle.java file is not a program (no main method) – you can’t run it. • To use this Rectangle class, you have to write another program which does have a main method. • Driver program / Client code • In this program you can create Rectangle objects and call methods in those objects. • The Rectangle program and its driver program must both be compiled in the same directory.
Testing Rectangles (Driver program) class RectTest { public static final void main(String[] args) { Rectangle page = new Rectangle(); page.setLength(30); page.setWidth(21); System.out.println(“The rectangle has a length of”); System.out.println(page.getLength()); System.out.println(“and a width of “); System.out.Println(page.getWidth());
System.out.println(“It’s area is “); System.out.println(page.area()); System.out.println(“It’s perimeter is “); System.out.println(page.perimeter()); } //end main } // end class
Encapsulation • All data & methods of Rectangles encapsulated. • Hidden the data from outside use • Provides protection of the data from malicious access • Public Interface • Methods are all public a.k.a. the public interface to Rectangles. • Only way to deal with Rectangle objects is through their (public) methods.