1 / 25

Creating Custom Classes

Creating Custom Classes. CSCI 142. What is a Class?. A template or blueprint for creating objects A “cookie cutter” Classes are defined by: The Standard API The Graphics API Other APIs You! Classes contain: Data Constructors Methods. A Class Has Data.

braith
Download Presentation

Creating Custom Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Creating CustomClasses CSCI 142

  2. What is a Class? • A template or blueprint for creating objects • A “cookie cutter” • Classes are defined by: • The Standard API • The Graphics API • Other APIs • You! • Classes contain: • Data • Constructors • Methods

  3. A Class Has Data • Data represents the properties of an object • Sometimes called state • Examples: • A GPen has x, y, color, and visibility • A Dog has gender, breed, and weight • A Car has…? • A Book has…?

  4. Class Data gender: M breed: unknown weight: 20.5 gender: F breed: beagle weight: 15.0 gender: M breed: schnauzer weight: 8.9

  5. Representing Class Data Encapsulation: Class data is not visible outside its class. • Data is represented as instance variables • Instance variables have class scope • Instance variables are private public class Dog { private char gender; private String breed; private double weight; } class header instance variables are private and have class scope

  6. A Class has Constructors • A constructor is used to instantiate the class, e.g. create a cookie from the cookie cutter • Constructors initialize instance variables • Defining a constructor • A constructor is always public • The constructor always has exactly the same name as the class • A constructor has no return type, not even void public Dog() { … }

  7. A Class has Constructors • Every class has at least one constructor • If you don’t create one, Java will create one for you! • Default constructors don’t have any parameters • Initialize instance variables to default values • Parameterized constructors accept one or more parameters • Initialize instance variables to values passed to the constructor

  8. WritingConstructors public class Dog { private char gender; private String breed; private double weight; public Dog() { gender = ‘N’; breed = “unknown”; weight = 0.0; } public Dog(char dogGender, String dogBreed, double dogWeight) { gender = dogGender; breed = dogBreed; weight = dogWeight; } } default constructor(no parameters) parameterized constructor

  9. Using a Custom Class • One class (a “client”) can use another class • Breakout uses GRect • No import statement needed if the classes are in the same folder • The client uses the constructor to instantiate the class • The client invokes methods on the object

  10. Using Your Class This is called a driver class, because it can be executed. import acm.program.ConsoleProgram; public class PetStore extends ConsoleProgram { public void run() { Dog d1 = new Dog(); Dog d2 = new Dog(‘M’, “boxer”, 10.2); } } default constructor parameterized constructor

  11. A Class has Methods • Methods represent the functionality or behavior of the class • Examples: • GPen has setColor(), getX(), and move() • Dog has setName(), getBreed(), and bark() • Car has …? • Methods can be public or private • Public methods are visible in the API and available to other classes • Public methods are used to interact with private data • Private methods are only available within their own class – sometimes called utility methods

  12. Common Class Methods • toString • Returns a String representation of an object • Setters • Used to change the value of a private instance variable • Getters • Used to return the value of a private instance variable All of these are optional.

  13. The toString() Method • Inherited from Object class • Should be overridden • Otherwise it prints the object’s memory address! • Returns a String representation of an object • Is called automatically when an object is passed to the println method • println(bucket);is equivalent toprintln(bucket.toString());

  14. Writing UsingtoString() toString() public class PetStore extendsConsoleProgram { public void run() { Dog d1 = new Dog(); Dog d2 = new Dog(‘M’, “boxer”, 10.2); println(d1.toString()); println(d2); } } public class Dog { private char gender; private String breed; private double weight; … public String toString() { String out = “”; out += gender + “ ”; out += breed + “ ”; out += weight; return out; } Two ways to print an object.

  15. Dog • char gender • String breed • double weight • + Dog() • + voidsetGender(chardogGender) • + voidsetBreed(String dogBreed) Set Methods • Return void • Accept one parameter,the same type as what they are setting • May be used to validate data • Also called mutators, because they change the value of instance variables return type parameter What would the set method for weight look like?

  16. Dog • char gender • String breed • double weight • + Dog() • + chargetGender() • + StringgetBreed() Get Methods • Return whatever data type they are getting • No parameters • Also called accessors, because they access instance variables return type parameter What would the get method for weight look like?

  17. Writing Set and Get Methods public class Dog { private char gender; private String breed; private double weight; public char getGender() { return gender; } public void setGender(char dogGender) { gender = dogGender; } … } get methods return a value and accept no parameters set methods return void and accept a parameter Write get and set methods for breed and weight

  18. The “this” Reference public class Dog { private char gender; private String breed; private double weight; … public void setGender(char gender) { this.gender = gender; } public void setBreed(String breed) { this.breed= breed; } The “this” reference refers to the object that invoked the method. Assigns the parameter gender to the instance variable gender.

  19. Using Set Methods for Data Validation public class Dog { private char gender; private String breed; private double weight; … public void setWeight(double weight) {if(weight > 0.0) {this.weight = weight;} } } How would you modify setGender to make sure that gender is N, M, or F?

  20. Using Setters and Getters public class PetStore extends ConsoleProgram { public void run() { Dog d1 = new Dog(); Dog d2 = new Dog(‘M’, “boxer”, 10.2); d1.setGender(‘F’); d1.setBreed(“poodle”); d1.setWeight(-5.4); println(“Weight of d1: ” + d1.getWeight()); println(“Gender of d2: ” + d2.getGender()); } } Print the breed of each dog. setters getters

  21. Other methods • A Dog might bark, sit, fetch, etc. public class Dog { … public String bark() {if(breed.equals(“poodle”)) {return “Yip!”;} else {return “Woof!”;}} } public class PetStoreextends ConsoleProgram { public void run() { Dog d1 = new Dog(); d1.setBreed(“poodle”); println(d1.bark()); Dog d2 = new Dog(‘M’, “boxer”, 10.2); println(d2.bark()); } }

  22. Public vs. Private Class2 Class1 Class Data public var private var Public Method Private Method

  23. Public vs. Private Class2 Class1 public class Class1 { public intpublicVar; private intprivateVar; } public class Class2 extends ConsoleProgram { public void run() { Class1 c = new Class1(); c.publicVar = 5; c.privateVar = 10; c.m1(); c.m2(); } } public void m1() { println(“hello”); m2(); } private void m2() { println(“hi”); }

  24. Dog • char gender • String breed • double weight • + Dog() • + Dog(char gender, String breed, double weight) • + void setGender(char gender) • + char getGender() • + void setBreed(String breed) • + String getBreed() • + void setWeight(double weight) • + double getWeight() • + String toString() Putting it All Together UML Static Class Diagram Data Constructors ClassMembers Methods

  25. The Anatomy of a Class

More Related