1k likes | 1.11k Views
CS121 Week 5: Day 1. Day 1: Writing Classes. Learning Objectives. Review object-oriented programming terminology . Discuss anatomy of a class in Java . Demonstrate how to create and use classes. Review OOP. OOP Terms-Review. Class Attributes Methods Object Encapsulation.
E N D
CS121 Week 5: Day 1 Day 1: Writing Classes
Learning Objectives • Review object-oriented programming terminology. • Discuss anatomy of a class in Java. • Demonstrate how to create and use classes.
OOP Terms-Review Class Attributes Methods Object Encapsulation
Every lego person has a shared set of attributes and methods. headHeight headWidth bodyColor etc. moveRightArm moveLeftArm etc. When we create a lego person instance, we define the exact values of the attributes. We can also add additional attributes and methods specific to an instance (more on this in CS221). Class Defines the attributes and methods of a type or class of objects. A blueprint from which objects are created. Classes define new, compound data types.
State name breed age isHungry Behaviors bark fetch sleep eat State characters length Behaviors getLength compareTo toUpperCase concatenate Object Objects in the real-world share two characteristics: state and behavior. Objects in programs often map to real world objects. They too have state and behavior. “Hello!”
“Mr. Orange” int width; int height; Color color; String name; height Attributes width Represent an object’s state. The values that make up the object.Can be primitive data types or other objects. Note: may also be referred to as fields, instance variables, properties.
“Mr. Orange” getWidth setWidth getHeight setHeight getArea draw What sequence of statements would getArea contain? Which attributes would it use? height Methods width Provide a way to execute an object’s behaviors.A group of programming statements that is given a name. Note: may also be referred to as functions, operations, actions.
A remote control is encapsulated. It hides the internal circuitry and provides public interfaces through the use of buttons.You can use it without knowing how it works. In Star Wars the shield gate provides controlled access to the planet through a single access point. Encapsulation The technique of controlling and protecting the data of an object. We can provide controlled access through public methods of an object. If we don’t want something to be exposed, we make it private. https://www.upwork.com/hiring/development/object-oriented-programming
Designing Classes Suppose we want to write a class to define a BroncoWeb account. What attributes would you need? What methods would it provide?
Class name. Attributes of object. publicclass Account{/* instance variables */private String username; .../* constructor */public Account(String username) { ... }/* other methods */public String toString() { ... }} How to construct a new object. Always the same name as the class name. Behaviors of object.
A Die Class Consider a single dice (a die). Attributes: face value number of sides Behaviors: roll get face value set face value (do we really want this?) print result
Constructors of a Die Class We can provide multiple ways to create a Die. Additional versions of a constructor are known as overloaded constructors. No two constructors can have the same parameter type and order.
Methods of a Die Class Most classes provide getter and setter methods for instance variables. They are also known as accessor and mutator methods.
Class name. Attributes of object. publicclass Die{/* instance variables */private int faceValue; .../* constructor */public Die() { ... }/* other methods */publicint roll() { ... }} How to construct a new object. Behaviors of object.
Instance Data Instance variables are named as such because each instance (aka object) of the class has its own value of the data. faceValue faceValue 3 1 die2 die1
Variable Scope The scope of a variable is the area in the program where it can be referenced and used. As a general rule, the scope is limited to within the curly braces in which a variable is defined. Instance variables have class scope. They can be used in all methods of the class (except static methods - more on this later). Local variables are defined in a method and can only be used in that method. The same applies to variables defined within loops and conditionals.
publicclass Die{/* instance variables */private int faceValue;private Random rand;/* other methods */publicint roll() { int newValue = rand.nextInt(faceValue) + 1; faceValue = newValue; … }/* more methods */} Class Scope Local Scope
The this Reference The this reference allows an object to refer to itself. That is, the this reference, used inside a method, refers to the object through which the method is being executed. The this reference can be used to distinguish the instance variables of a class from corresponding method parameters with the same names. Thus we can reuse the instance variable names as formal parameter names, avoiding having to create unnecessary new names.
Methods A method consists of a header and body. publicint getFaceValue() {return faceValue; } publicvoid setFaceValue(int value) { faceValue = value; }
Method Header The method header includes the visibility modifier, return type, method name, and formal parameter list. publicint getFaceValue () {return faceValue; } publicvoid setFaceValue (int value) { faceValue = value; }
Method Body - Return Types The method body includes statements for what the method should do. If the return type is void, no return statement is needed. If the return type is defined as any other type, must return a value of that type. publicint getFaceValue () {return faceValue; } publicvoid setFaceValue (int value) { faceValue = value; }
Method Body - Using Parameters The method body can use the parameters passed through the parameter list by name. publicint getFaceValue () {return faceValue; } publicvoid setFaceValue (int value) { faceValue = value; }
Encapsulation Two views of an object: • internal: the details of the variables and methods that make up a class • external: the services that an object provides and how the objects interacts with the rest of the system From the external view, an object is an encapsulated entity, providing a set of specific services These services define the interface to the object. Clients should not be able to access an object’s variables directly. Any changes to the object’s state should be made by that object’s methods. That is, an object should be self-governing.
Visibility Modifiers Encapsulation is provided via the use of visibility modifiers. We will focus on 2 of the 4 visibility modifier: public and private. Instance variables and methods of a class declared public can be referenced from any other class. Instance variables and methods of a class declared private can be referenced only within that class.
Encapsulation Best Practices To enforce encapsulation, instance variables should always be declared with private visibility. Then we can allow controlled access using special methods know as accessors and mutators. It is acceptable to give a constant instance variable public visibility. (Why?) Methods that provide service to clients should be declared public. A method created simply to assist a service method is called a support method. Support methods are declared private.
Design and Implement a Class Sphere Dog Coin Outline what a class for each of these three items would look like. Make sure to list all of the attributes and how you would want to find those attributes. Begin to play with implementation of these methods.
Terminology Review • Class • Object • Attribute • Method • Constructor • Encapsulation • Instance Variable • Local Variable • Scope • Parameter list • Return type • Visibility Modifier
CS121 Week 5: Day 2 Day 2: Writing Methods
Learning Objectives • Review anatomy of a method in Java. • Demonstrate flow of control with method invocations (calls). • Show how to design and use methods. • Discuss differences between static and non-static methods. • Understand method overloading - variations on a theme.
Methods A method consists of a header and body. publicint getFaceValue() {return faceValue; } publicvoid setFaceValue(int value) { faceValue = value; }
Method Header The method header includes the visibility modifier, return type, method name, and formal parameter list. publicint getFaceValue () {return faceValue; } publicvoid setFaceValue (int value) { faceValue = value; }
Method Body - Return Types The method body includes statements for what the method should do. If the return type is void, no return statement is needed. If the return type is defined as any other type, must return a value of that type. publicint getFaceValue() {return faceValue; } publicvoid setFaceValue(int value) { faceValue = value; }
Method Body - Using Parameters The method body can use the parameters passed through the parameter list by name. publicint getFaceValue() {return faceValue; } publicvoid setFaceValue (int value) { faceValue = value; }
Method Invocation What happens when you call a method?
Max Of Three Using Methods Let’s write a method that takes three integer values as input and returns the value of the largest integer. publicint maxOfThree (int n1, int n2, int n3) { int max = Math.max(n1, n2); max = Math.max(max, n3); return max; }
somewhere in computer memory Invoking the Method public static void main(String[] args) { int a = 8, b = 5, c = 10;int max; max = maxOfThree(a, b, c); System.out.println(max); } 8 5 10 (int) (int) (int) (int) max a b c publicint maxOfThree(int x, int y, int z){int max = Math.max(x, y); max = Math.max(max, z);return max;}
somewhere in computer memory Invoking the Method public static void main(String[] args) { int a = 8, b = 5, c = 10;int max; max = maxOfThree(a, b, c); System.out.println(max); } 8 5 10 (int) (int) (int) (int) (int) (int) (int) (int) max max a c x b y z publicint maxOfThree(int x, int y, int z){int max = Math.max(x, y); max = Math.max(max, z);return max;}
somewhere in computer memory Invoking the Method public static void main(String[] args) { int a = 8, b = 5, c = 10;int max; max = maxOfThree(a, b, c); System.out.println(max); } 8 5 10 (int) (int) (int) (int) (int) (int) (int) (int) max max c x y b z a publicint maxOfThree(int x, int y, int z){int max = Math.max(x, y); max = Math.max(max, z);return max;} 8 5 10
somewhere in computer memory Invoking the Method public static void main(String[] args) { int a = 8, b = 5, c = 10;int max; max = maxOfThree(a, b, c); System.out.println(max); } 8 5 10 (int) (int) (int) (int) (int) (int) (int) (int) max max y a b c z x publicint maxOfThree(int x, int y, int z){int max = Math.max(x, y); max = Math.max(max, z);return max;} 8 5 10 8
somewhere in computer memory Invoking the Method public static void main(String[] args) { int a = 8, b = 5, c = 10;int max; max = maxOfThree(a, b, c); System.out.println(max); } 8 5 10 10 (int) (int) (int) (int) (int) (int) (int) (int) max max z x c b a y publicint maxOfThree(int x, int y, int z){int max = Math.max(x, y); max = Math.max(max, z);return max;} 8 5 10
somewhere in computer memory Invoking the Method public static void main(String[] args) { int a = 8, b = 5, c = 10;int max; max = maxOfThree(a, b, c); System.out.println(max); } 10 8 10 5 10 10 5 8 (int) (int) (int) (int) (int) (int) (int) (int) max max a x c y b z publicint maxOfThree(int x, int y, int z){int max = Math.max(x, y); max = Math.max(max, z);return max;}
somewhere in computer memory Invoking the Method public static void main(String[] args) { int a = 8, b = 5, c = 10;int max; max = maxOfThree(a, b, c); System.out.println(max); // prints 10 } 10 8 5 10 (int) (int) (int) (int) max a b c publicint maxOfThree(int x, int y, int z){int max = Math.max(x, y); max = Math.max(max, z);return max;}
Static Methods (also called Class Methods)
Instance Methods Methods that are defined as behaviors of a class are called instance methods. You must create an instance of the class in order to invoke the method on that instance. Die die = new Die();die.getFaceValue();die.roll(); Each instance executes the method using it’s unique instance data.