Review of CSCI 1226 More of What You Should Already Know.

Slides:



Advertisements
Similar presentations
Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
Advertisements

CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
TOPIC 12 CREATING CLASSES PART 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson,
Week 10: Objects and Classes 1.  There are two classifications of types in Java  Primitive types:  int  double  boolean  char  Object types: 
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Chapter 5- Even more about objects and methods. Overview n Designing methods n Methods, methods, methods n Overloading methods n Constructor methods n.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Hello AP Computer Science!. What are some of the things that you have used computers for?
Methods Material from Chapters 5 & 6. Terminology  Method, function, procedure, subroutine  all mean approximately the same thing »functions may return.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create.
Introduction to Computation and Problem Solving Class 9: Static Methods and Data Members Prof. Steven R. Lerman and Dr. V. Judson Harward.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
10-Nov-15 Java Object Oriented Programming What is it?
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Working With Objects Tonga Institute of Higher Education.
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
Hello Computer Science!. Below is an example of a Hello World program in JAVA. While it is only three lines of code, there are many things that are happening.
Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
Creating a GUI Class An example of class design using inheritance and interfaces.
Methods OR HOW TO MAKE A BIG PROGRAM SEEM SMALLER.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,
Review of CSCI 1226 What You Should Already Know.
Data, Classes, and Objects Classes with Data Classes for Data (Chapter 5)
3-July-2002cse142-D2-Methods © 2002 University of Washington1 Methods CSE 142, Summer 2002 Computer Programming 1
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Data, Classes, and Objects
More on Objects and Classes
Static and non-Static Chapter 5.
Data, Classes, and Objects
Object Based Programming
More Methods and Arrays
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Barb Ericson Georgia Institute of Technology June 2005
Object-Oriented Programming
Barb Ericson Georgia Institute of Technology Oct 2005
What You Should Already Know
Presentation transcript:

Review of CSCI 1226 More of What You Should Already Know

Review of Chapters 5 to 7 n Methods »(AKA subroutines, functions, procedures)  understand method calls  create and use our own methods  organize methods into classes n Data type classes  create and use a data type class

Using Methods n We’ve been using methods from the start  print and println are methods (as is printf)  nextInt, nextDouble, next, and nextLine, too  equals, equalsIgnoreCase, startsWith, and all those other things we can ask a String to do  pow, sqrt, max, min, and all those other things we can ask Math to do

Why Do We Have Methods? n Code Re-use  Doing “same” thing in multiple places » we do a lot of printing! n Code Hiding (Encapsulation)  Secret  Implementation independence n Code Abstraction  Top-down design

Parts of a Method Call n All method calls are alike:  Math.pow(5, 7)  kbd.nextInt()  resp.equalsIgnoreCase(“yes”)  Someone.doSomething(with, these) »Someone (Math, kbd, resp, …) »doSomething (pow, nextInt, equalsIgnoreCase, …) »(with, these) ((5, 7), (), (“yes”))

Someone? n Can ask a class or an object  class name starts with a capital letter (Math)  object name starts with a little letter (kbd) n Objects are variables with a class data type Scanner kbd = new Scanner(System.in); String resp = kbd.nextLine(); n Methods are declared in that class  class Math, class Scanner, class String, …

doSomething? n Name of the method says what it does…  print, println, … »verb phrase in the imperative (do, be) n …or what it gives us…  length, nextInt, nextLine, … »noun phrase n …or what it tells us  equals, equalsIgnoreCase, startsWith »verb phrase in the declarative (does, is)

With These? n Method needs more information n “Arguments” are given to the method »we also say that the method takes arguments  Math.pow(5, 7) – 5 and 7 are both arguments  resp.startsWith(“y”) – “y” is the (one) argument n Some methods take no arguments  kbd.nextLine() – needs no more information

Void Methods n Some methods are complete commands in themselves  telling the computer to do something System.out.println(“A complete command”); n These methods cannot be used as part of a command String resp = System.out.println(“What???”);

Return Values n Some methods return values  Math.sqrt(x) returns the square root of x  kbd.nextInt() returns the next (int) value n These (usually) used as part of a command int n = kbd.nextInt(); double y = Math.sqrt(n); if (resp.startsWith(s)) { n But may be used alone sometimes kbd.nextLine(); // we don’t care what the line was!

“Chaining” Method Calls n When one method returns an object value…  e.g. resp.toUpperCase()  if resp is “yes”, resp.toUpperCase() is “YES” n …we can ask that object a question  e.g. resp.toUpperCase().startsWith(“Y”)  resp is “yes” (which doesn’t start with “Y”)  resp.toUpperCase() is “YES”  “YES” does start with “Y”

The Job of the Method n Every method has a job to do  print a line, get the next int, … n Call the method  the job gets done  that’s what the method is there for n How the method does the job…  the body/definition of the method n …is just details!  caller (“client”) just wants it done

Make Gift Exchange List n Plan:  get a list of everyone giving presents  make the list of everyone getting presents »(it’s the same list at first)  for each person in the list giving presents: »choose someone else from the list getting presents »remove that someone from the list getting presents »print a message saying who this person’s buying for

Make Gift Exchange List public static void main(String[] args) { // get a list of everyone giving presents // make the list of everyone getting presents // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for }

Make Gift Exchange List public static void main(String[] args) { // get a list of everyone giving presents String[] giving = GiftExchange.getGivingList(); // make the list of everyone getting presents // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for } What’s the return type of getGivingList?

Designing Methods n Need to read a list of names  could just write the code here in main  but that would make main big and hard to read  and also require creating variables that we don’t need anywhere else in main  and right now I’m thinking “big picture” »I need this done, but I don’t care (right now) about the details  so create a method to do it for me

Static Methods calling Methods n Location of the method is the current class  method getGivingList is in class GiftExchange GiftExchange.getGivingList() n NOTE: NOT this.getGivingList() String[] giving = this.getGivingList();  main is static – does not belong to an object »there is no “this” in a static method! non-static variable this cannot be referenced from a static context

Calling Own-Class Methods n When the method is in the same class, you don’t need to say the class name String[] giving = getGivingList();  caller is static  called method is static, too String[] giving = getGivingList(); String[] giving = getGivingList();…… public String[] getGivingList { …} non-static method getGivingList() cannot be referenced from a static context But NOTE: the actual mistake is HERE! getGivingList should be declared static.

Make Gift Exchange List public static void main(String[] args) { // get a list of everyone giving presents String[] giving = getGivingList(); // make the list of everyone getting presents // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for } public static String[] getGivingList() {// STUB! return new String[1]; }

Make Gift Exchange List public static void main(String[] args) { // get a list of everyone giving presents String[] giving = getGivingList(); // make the list of everyone getting presents String[] getting = copyArray(giving); // for each person in the list giving presents: // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for } What’s the argument type of copyArray?

Make Gift Exchange List // get a list of everyone giving presents String[] giving = getGivingList(); // make the list of everyone getting presents String[] getting = copyArray(giving); // for each person in the list giving presents: for (int p = 0; p < giving.length; ++p) { // choose someone else from the list getting presents // remove that someone from the list getting presents // print a message saying who this person’s buying for }

Make Gift Exchange List // for each person in the list giving presents: for (int p = 0; p < giving.length; ++p) { // choose someone else from the list getting presents String name = chooseSomeone(getting, giving[p]); // remove that someone from the list getting presents removeName(getting, name); // print a message saying who this person’s buying for System.out.println(giving[p] + “ buys for ” + name); } What are the tasks of chooseSomeone and removeName? What are their argument types? What are they for?

Exercise n Write stubs for the following functions String[] giving = getGivingList(); String[] getting = copyArray(giving); int p = 0; String name = chooseSomeone(getting, giving[p]); removeName(getting, name);  this is exactly what we did before! »we will be reading some data in the methods »recall how to create and return an array!

Tasks/Jobs for Methods n Job is whatever the pseudo-code says  you did write pseudo-code, right??? // choose someone else from the list getting presents String name = chooseSomeone(getting, giving[p]); // remove that someone from the list getting presents removeName(getting, name);  write the javadoc to reflect the job and the purpose of the parameters  write the method that way, too!

Javadoc for chooseSomeone n Sample javadoc /** * pick a name (not the given one) from a list * pick a name (not the given one) from a list * gettingList list of names to choose from gettingList list of names to choose from givingName name NOT to choose givingName name NOT to choose a name from gettingList that’s a name from gettingList that’s * not equals to givingName. * not equals to givingName. */ */  choose suitable parameter names »can’t use giving[p] as a parameter name!

Exercise n Write a javadoc for removeName // remove that someone from the list getting presents removeName(getting, name);

Building Your Program n Create pseudo-code n Create main method, with method calls n Create stubs for the methods called n Repeat until your program is complete  run your program to make sure it’s OK »fix any errors you find  implement another method

getGivingList public static String[] getGivingList() { // create a scanner // create a scanner // ask for and read how many names there will be // ask for and read how many names there will be // create a String array of the appropriate size // create a String array of the appropriate size // for each element of the array // for each element of the array // prompt for and read a name into that element // prompt for and read a name into that element // return the array // return the array // STUB – delete when above is complete: return new String[1]; return new String[1];}

removeName public static void removeName(String[] list, String name) { // for each element of the array // for each element of the array for (int i = 0; i <list.length; ++ i) { for (int i = 0; i <list.length; ++ i) { // if that element is equals to name // if that element is equals to name if (list[i].equals(name)) { if (list[i].equals(name)) { // remove that element // remove that element list[i] = “”; list[i] = “”; } }} Angela Barrak Vladimir David Vladimir Note: we can name the array parameter anything we want. It’s going to be the same list of names that main gave us.

Organizing Methods into Classes n Above methods are just for the program n May want methods that are generally useful  to do math (Math.pow, Math.sqrt, …)  for arrays (Arrays.toString, Arrays.sort, …)  we can make our own public class Converter { public class Utilities{  methods written same way  just leave out main! I use green text for code in a non-program class.

Classes vs. Objects n Classes can be used right away Utilities.printTitle(“Utilities Demo”); »so long as we can “see” them n Objects need to be created »except for Strings, which are so massively useful… Scanner kbd = new Scanner(System.in);  objects contain data  different objects have different data  methods are mostly about that data

Object Oriented Programming n Programming arranged around objects  main program creates the objects  objects hold the data  objects call each others’ methods  objects interact to achieve program goal n Very important in GUI programs  Graphical User Interface »WIMP (Windows, Icons, Menus, Pointers) interface

What are Objects? n An object in a program often represents a real-world object…  an animal, a vehicle, a person, a university, … n …or some abstract object…  a colour, a shape, a species, … n …or some thing the program needs to track  a string, a window, a GUI button, …

Object (Data Type) Classes n What kind of object it is  its data type is a Class String s1, s2;// s1 & s2 are Strings Scanner kbd, str;// kbd & str are Scanners Animal rover, hammy;// rover & hammy are Animals Color c1, c2;// c1 & c2 are Colors JButton okButton, cancelButton;// … are JButtons n Objects in the same class do the same kinds of things To use Color & JButton, you need to import java.awt.Color; import javax.swing.JButton;

Declaring Objects n Most Java objects created using new »usually with arguments »arguments depend on the class kbd = new Scanner(System.in); rover = new Animal(Animal.DOG);// I made this up! c1 = new Color(255, 127, 0);// This is orange okButton = new JButton(“OK”); »not Strings, tho’ s1 = “Strings are special!”; s2 = new String(“But this works, too!”); Remember to import java.awt.Color; import javax.swing.JButton;

Object Data and Methods n Each kind of object has its own kind of data  String has array of characters  Color has red, green, and blue components n Methods access that data  get pieces of it, answer questions about it, change it name characters Mark Young orange red green blue

Making Our Own Data Types n When we want to represent objects but can’t find an existing class for that kind of object  e.g. Student objects n Identify the objects’ data and operations  data: A-number, name, address, grades, …  operations: change name, print address label, set grades, calculate GPA, … n Create a class for this kind of object

Instance Variables public class Student { public final String A_NUMBER;// A00... private String name;// family name, givens private int pctGrade;// …}  instance variables are declared private (not public) »don’t let anyone change them without our permission  may be final (never going to change) »these may be declared public

Declaring a Student n Give A#, name and grade when create Student s1, s2; s1 = new Student(“Dent, Stu”, 81); s2 = new Student(“Tudiaunt, A.”, 78);  or can combine the steps: Student s3 = new Student(“No, Dr.”, 0);  arguments are name (String) and grade (int) »values for each (or some of the) instance variable

Student Constructor n Constructor “builds” the Student object  gives a value to each of the instance variables public final String A_NUMBER;// A00… private String name;// Last, First private int grade;// public Student(String name, int grade) { this.name = name; this.name = name; this.grade = grade;// should check this value! this.grade = grade;// should check this value! … // A_NUMBER still needs a value … // A_NUMBER still needs a value} note how “name” and “this.name” are used.

Giving Values n Constructor’s job is to give values to all instance variables  client may say what values to use »may need to check those values to see if they’re OK  client may leave some values unstated »we choose those values ourselves

Checking Values n Grade should be  write a method to check if it is in that range public static boolean isValidGrade(int g) { return 0 <= g && g <= 100; return 0 <= g && g <= 100;} n Note: static method  whether grade is valid is same for all Students »static  same for every object of this class »non-static  diff. objects may give diff. answers What should we do about that “magic” number???

Choosing Values n May use a reasonable default value  if they don’t say what grade, set grade to 0 n May generate our own values  A-numbers automatically generated »1 st Student  A »2 nd Student  A  static method to generate those numbers  static variable to remember the count

Generating A-Numbers n Static variable to remember what’s next private static int howManyStudents = 0; n Method to generate next A-Number  increment howManyStudents & generate String private static String nextANumber() { ++howManyStudents; ++howManyStudents; return String.format(“A%08d”, howManyStudents); return String.format(“A%08d”, howManyStudents);}  method is private so others can’t use it! »they might try to misuse it!

Student Constructor n All instance variables given values!  gives a value to each of the instance variables public Student(String name, int grade) { this.name = name; this.name = name; if (isValidGrade(grade)) { if (isValidGrade(grade)) { this.grade = grade; this.grade = grade; } else { } else { this.grade = 0; this.grade = 0; } A_NUMBER = nextANumber(); A_NUMBER = nextANumber();} Good practice: call only static methods from your constructor.

Overloaded Constructor n May want more than one constructor  let client decide how much/what info. to give Student s1 = new Student(“Alice”, 100); Student s2 = new Student(“Ben”);  need a constructor that takes just a String n Re-use code as much as possible  have new constructor call old constructor public Student(String name) { this(name, 0);// use name given; set grade to 0 this(name, 0);// use name given; set grade to 0}

Methods to Get Information n Instance variables are private  client can’t use them! System.out.println(stu.name); n “Getters”  usually named get + name of instance variable »but capitalized in camelCase System.out.println(stu.getName()); System.out.println(stu.getPctGrade()); name is private in Student!

Student “Getters” n Getters are very simple!  just return the instance variable »method return type same as type of variable public String getName() { return name; return name;} public String getPctGrade() { return grade; return grade;} public! Anyone can ask! No static! Each student has own name!

Methods to Change Information n Some fields may need to be changed  name and grade, for example  student number should NOT be changed! n Need a method to do that, too! stu.name = “Dummikins, Dummy”; n Methods called “setters”  named “set” + name of instance variable stu.setName(“Dummikins, Dummy”); stu.setPctGrade( ); name is private in Student!

Setters n Given the new value the caller wants  normally we will use that value public static void setName(String newName) { name = newName; name = newName;}  but we might want to reject it public static void setPctGrade(int newGrade) { if (isValidGrade(grade)) { if (isValidGrade(grade)) { grade = newGrade; grade = newGrade; }} May want to print an error message…

More Methods n Can create other methods if you want stu.printRecord();  prints stu’s name, A-number and grade  just uses System.out.println »that’s OK because it’s part of the job! stu number name pctGrade A “Dent, Stu” 81 A-Number: A Name: Dent, Stu Grade: 81

Class (static) Methods n Ask for letter grade corresponding to pct String lg = Student.letterGradeFor(stu.getPctGrade());  doesn’t matter who you ask, answer is same »static method! public static String letterGradeFor(int g) { if (g >= 80) return “A”; else if (g >= 70) return “B”; … if (g >= 80) return “A”; else if (g >= 70) return “B”; …}

More Instance Methods n Make it easier to get Student’s letter grade S.o.pln(stu.getName() + “ got ” + stu.getLetterGrade());  asks student object for its letter grade  method is like a getter… public String getLetterGrade() { return this.getLetterGradeFor(this.getPctGrade()); return this.getLetterGradeFor(this.getPctGrade());}  …but don’t create a letterGrade variable!

Programming Principles n Make it impossible (or very hard) for the client to do stupid/malicious things  can’t set pctGrade outside  can’t set pctGrade to 100 and letterGrade to F n Make it easy for client to do common things  ask a Student for their letter grade, even tho’ could ask Student for their pctGrade and then translate it using “cascading if” control  getLetterGrade is a convenience

Another Convenience n Printing an object doesn’t work very well! Student stu = new Student(“Pat”, 80); System.out.println(stu);  prints something like  want something like Pat (A ) n toString method tells how to convert an object to a String (which can be printed) System.out.println(stu.toString());

The toString Method n Does not print anything!  it returns the String that will get public String toString() { return name + “ (” + A_NUMBER + “)” return name + “ (” + A_NUMBER + “)”} is optional, but NetBeans will tell you to put it there »I’ll explain what it means later this term

Using the toString method n You can ask for it: Student s = new Student(“Pat”, 80); System.out.println(s.toString()); n But you don’t actually need to! Student s = new Student(“Pat”, 80); System.out.println(s);  println will actually change it to String itself »one of the conveniences println provides!

Questions? n Next Time  material from chapters 1-7 that we skipped in CSCI 1226