250 likes | 419 Views
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.
E N D
Creating CustomClasses 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 • 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…?
Class Data gender: M breed: unknown weight: 20.5 gender: F breed: beagle weight: 15.0 gender: M breed: schnauzer weight: 8.9
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
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() { … }
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
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
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
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
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
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.
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());
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.
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?
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?
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
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.
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?
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
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()); } }
Public vs. Private Class2 Class1 Class Data public var private var Public Method Private Method
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”); }
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