Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Creating Classes. 2 Writing Classes Thus far, we have mainly used existing classes in the Java library  (also main classes for executing) True object-oriented.

Similar presentations


Presentation on theme: "1 Creating Classes. 2 Writing Classes Thus far, we have mainly used existing classes in the Java library  (also main classes for executing) True object-oriented."— Presentation transcript:

1 1 Creating Classes

2 2 Writing Classes Thus far, we have mainly used existing classes in the Java library  (also main classes for executing) True object-oriented programming is all about writing our own classes  Writing classes with well-defined characteristics and functionality

3 3 What we Need In order to write our own classes, we need to specify:  constructors that can be used to create an instance  data members to hold the instance’s state  the methods that can be used in an instance  the behaviour of the methods

4 4 Example in the Text (slightly generalized) A class representing a generic die  Has some number of sides Specify in the constructor  Is showing some number Use a data member  Can be rolled Provide a method to change the number shown Given this class, we can create a whole bunch of die objects

5 5 Basics We have already created “code-library” type classes  The difference now is that not everything is static and we introduce some data members  Also, we think the class as representing some type of object… not just a collection of numbers We will illustrate with a class Student representing an SFU Student

6 6 Basics Typical setup: int size, weight; char category; Data declarations Method declarations

7 7 Instance Data Class variables/data members that hold the state of the object  e.g. for a Student : name and student ID Implemented as variables in the class  Not in the scope of some method  It is data associated with the object… not with implementation of some method

8 8 Defining Data Members Defined just like other variables… just not in a method class Student { private String firstName, lastName; private long studentNumber; } These can be used from any of the methods in the class

9 9 Using Data Members Each instance of a class defines it’s own data members  Two Student objects will have different studentNumber values  Modifying s1.studentNumber does not affect s2.studentNumber (s1 and s2 are references to Student objects)

10 10 Access Control Note: the data members were defined as private  Data members should always be private  Can not be used/changed by any methods outside the class  e.g. Student s = new Student(); s.firstName = “Joe”; // ERROR! All access through getter and setter methods

11 11 Methods Just like methods in code-library classes Except: Want to make a copy for each instance, so we do not declare static class Student { private String firstName, lastName; public void setFName(String name) { if(name.length()>0) firstName=name; }

12 12 Methods Methods can be used to construct getters and setters  … or any other operations that are needed class Student { …// declare data members public void setFName(String name){…} public String getFName(){…} public void addMark(…){…} // public and non-static: a visible part // of each instance }

13 13 Special Methods: toString() Any class may define a toString() method, which has a special meaning When an object is passed to a print command, toString() is called e.g. in Student, the toString() method might return the student’s name or ID number Typically, data members are used to give a “nice label”

14 14 Special Methods: Constructors A constructor is a special method that is called when an object is created  used to instantiate instance data Constructors have no return type  not even void Constructors have the same name as the class class Student {…. Student(long stunum) { studentNumber = stunum; } …}

15 15 Constructors Parameters in a constructor passed with the new command  Student s = new Student(432553342); There can be more than one constructor  We saw this with String objects

16 16 UML Diagrams UML stands for the Unified Modeling Language UML diagrams show relationships among classes and objects A UML class diagram consists of one or more classes, each with sections for the class name, attributes (data), and operations (methods) Lines between classes represent associations A dotted arrow shows that one class uses the other (calls its methods)

17 17 UML Class Diagrams A UML class diagram for the RollingDice program in the text: RollingDice main (args : String[]) : void Die faceValue : int roll() : int setFaceValue (int value) : void getFaceValue() : int toString() : String

18 18 Encapsulation Two views of an object:  internal – the details of the data members and methods that define it  external – the services that the object provides and how the object interacts with other objects From the external view, the object is an encapsulated entity, providing specific services These services define the interface of the object

19 19 Encapsulation One object may use the services of another The client using the services (methods) should not need detailed knowledge of how the services are provided  All they see are the public methods We should make it difficult (impossible) to access variables directly That is, the object should be self-governing

20 20 Encapsulation An encapsulated object can be thought of as a black box -- its inner workings are hidden from the client Methods Data Client

21 21 How? Declare all data members private (pretty much)

22 22 Why? Why declare all data members as private? Since variables can only be changed by the class, the class author can control access  Methods can be designed so data is always in a useful state  e.g. studentNumber must be 9 digits, positive… Other methods can then assume meaningful data in these variables

23 23 Why? When debugging the class, we don’t have to worry about outside code modifying variables  Makes debugging much easier  Like local variables in a function/method, but defined for the whole instance The object design can then assume that only internal code has changed variables  e.g. studentNumber will always have 9 digits

24 24 Why? public data members violate encapsulation by allowing other objects to “reach in” and change things  the other object might not know what it is doing  reaching into a black box and pushing things around….

25 25 One Exception It is usually considered acceptable to declare constants with public visibility public final MAX = 10; The value of MAX can be accessed from other classes Does not violate encapsulation – the value can not be changed

26 26 Method Visibility Public methods provide services to other methods  sometimes public methods are called service methods Some methods are defined just to assist with services – these are called support methods  e.g. the discrim method in quadratic Support methods should be declared private

27 27 Visibility Modifiers Summary publicprivate Variables Methods Provide services to clients Support other methods in the class Enforce encapsulation Violate encapsulation

28 28 Example public class GasTank { public final double MINGAS = 0; public final double MAXGAS = 40; private double AmountGas; GasTank(double d) { AmountGas = d; } public void addGas(double d) { AmountGas += d; } …//more methods }

29 29 What Goes Wrong? Is access ok?  public constants (OK)  private class variable (OK)  public mutator (OK) But what about this (in a different method): GasTank gt = new GasTank(30); gt.addGas(30);  The gas has exceeded MAX!

30 30 Interface Design This is why we want mutator methods and encapsulation…. but we need to worry about interface design… Controlling access only helps if we do it right In this case, addGas(d) could just set the gas at MAXGAS instead of going over Better solution… send a warning or error…

31 31 A More Detailed Example Student.java StudentTest.java


Download ppt "1 Creating Classes. 2 Writing Classes Thus far, we have mainly used existing classes in the Java library  (also main classes for executing) True object-oriented."

Similar presentations


Ads by Google