Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,

Similar presentations


Presentation on theme: "Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,"— Presentation transcript:

1 Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects, and Methods

2 Topic 8Classes, Objects and Methods 2 OO revision l Objects »A capsule that contains 2 important parts –State (attributes or data) l What does the object know? –Behaviour (methods or functions) l What does the object know how to do? »E.g. Cars, employee records, etc. l 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. l Instantiate »An object that satisfies the class definition is said to instantiate the class.

3 Topic 8Classes, Objects and Methods 3 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

4 Topic 8Classes, Objects and Methods 4 General class syntax: modifier(s) class ClassIdentifier { classMembers } l Modifier(s) »Used to alter the behaviour of the class »public, private, static l ClassMembers »Named constants, variable declarations and/or methods »Can also be declared as public, private or static

5 Topic 8Classes, Objects and Methods 5 class Car { double fuelAmount = 0.0; double speed = 0.0; String licencePlate = “ “; }

6 Topic 8Classes, Objects and Methods 6 Instantiations of the Class Car 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” First Instantiation Object name: patsCar Second Instantiation Object name: suesCar Third Instantiation Object name: ronsCar amount of fuel: 2 litres speed: 75 km / hr licence plate: “351 WLF”

7 Topic 8Classes, Objects and Methods 7 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.

8 Topic 8Classes, Objects and Methods 8 Car Example continued….. Car Object »Instantiates the Car class. »Each object has a name  these are variables of type Car. –patsCar, suesCar, ronsCar

9 Topic 8Classes, Objects and Methods 9 Types of methods l Every method belongs to a class. l Method definitions given inside the definition of the class. l Single value methods »Used to return Java values l 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

10 Topic 8Classes, Objects and Methods 10 Single-value Method Definitions: public Type_Returned Method_Name(parameters) { list of statements  must contain a return statement } public double getFuelAt() { return fuelAmount; }

11 Topic 8Classes, Objects and Methods 11 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 }

12 Topic 8Classes, Objects and Methods 12 PARAMETERS l Formal parameters »Used in the method definition l Actual parameters »Value of the variable that is passed to the method when that method is called/invoked.

13 Topic 8Classes, Objects and Methods 13 Method invocation / Call a method Object_name.method_name(); l Method defined in a class is usually invoked using an object of that class  object calling a method

14 Topic 8Classes, Objects and Methods 14 CONSTRUCTORS: l Special type of method. »Not void »Does not return a value l One or more found in every class. l Has the same name as the class & it executes automatically when an object of that class is created. l Used to guarantee that the instance variables of the class are initialised to specific values. l Types of constructors »With parameters »Without parameters (known as the default constructor)

15 Topic 8Classes, Objects and Methods 15 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();

16 Topic 8Classes, Objects and Methods 16 The Member Access Separator l Once you’ve constructed a car, you want to do something with it. l To access the fields or methods of the car you use the. (dot) separator. »Selects a specific member of a Car object by name. l 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”);

17 Topic 8Classes, Objects and Methods 17 Class file REMINDERS l Each Java class definition should be a separate file l Use the same name for the class and the file, except add ".java" to the file name l For now put all the classes you need to run a program in the same directory

18 Topic 8Classes, Objects and Methods 18 Standard methods for a class l Constructor methods »Methods which initialise the object when it is first created. l Reader / Get methods »Methods which allow outside codes to view or get copies of the object’s state. l Writer / Set methods »Methods which allow outside codes to assign new values for the object’s state. l Mutator methods »Methods which allow outside codes to modify the state of an object. l Query methods »Methods which test the state of an object.

19 Topic 8Classes, Objects and Methods 19 class Car { double fuelAmount = 0.0; double speed = 0.0; String licencePlate = “ “; void setMaxSpeed() { speed = 200.0; }

20 Topic 8Classes, Objects and Methods 20 SIMPLE CLASS EXERCISE!!! l Consider a simple class of objects which represent Rectangles. A brief (& shallow) analysis will reveal the state & behaviour of our simple Rectangle objects. l The state (knows its?) »length (integer) »width (integer) l 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

21 Topic 8Classes, Objects and Methods 21 // 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;

22 Topic 8Classes, Objects and Methods 22 // Behaviour (instance methods) // Constructor public Rectangle() { length = 0; width = 0; }

23 Topic 8Classes, Objects and Methods 23 // Writer or Set methods public void setLength( int len ) { length = len; } public void setWidth( int wid ) { width = wid; }

24 Topic 8Classes, Objects and Methods 24 // Reader or Accessor methods public int getLength() { return length; } public int getWidth() { return width; }

25 Topic 8Classes, Objects and Methods 25 // Other services public int area() { int the_area = length * width; return the_area; } public int perimeter() { int perim; perim = 2 * (length + width); return perim; }

26 Topic 8Classes, Objects and Methods 26 public boolean isLegal() { if( length >= 0 && width >= 0 ) return true; else return false; } }// end class

27 Topic 8Classes, Objects and Methods 27 Constructor Methods l Must have same name as the class. l Does not have any return type »Not even void l Creates a new instance of the class. »Initialises all the variables & does any work necessary to prepare the class to be used. l If no constructor is exists, Java provides a generic one that takes no arguments. »Better to write your own constructor.

28 Topic 8Classes, Objects and Methods 28 l 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; }

29 Topic 8Classes, Objects and Methods 29 Access Control l public »Variable or method is available to other programs. l 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. l protected »If you want access restricted to subclasses & members of the same package.

30 Topic 8Classes, Objects and Methods 30 Instance / Non-static Methods None of the methods in the Rectangle class are labelled static. l These types of methods are designed to be accessed via objects.

31 Topic 8Classes, Objects and Methods 31 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.

32 Topic 8Classes, Objects and Methods 32 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());

33 Topic 8Classes, Objects and Methods 33 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

34 Topic 8Classes, Objects and Methods 34 l Encapsulation »All data & methods of Rectangles encapsulated. –Hidden the data from outside use »Provides protection of the data from malicious access l 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.


Download ppt "Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,"

Similar presentations


Ads by Google