COMP 110: Introduction to Programming Tyler Johnson Feb 18, 2009 MWF 11:00AM-12:15PM Sitterson 014
COMP 110: Spring Announcements Program 2 due tonight by midnight Lab 4 due tomorrow by midnight Midterm Wed, Mar 4th
COMP 110: Spring Program 1
COMP 110: Spring Questions?
COMP 110: Spring Today in COMP 110 Classes & Methods
COMP 110: Spring Defining the Class Student public class Student { public String name; public int year; public double GPA; public String major; //... public String getMajor() { return major; } public void increaseYear() { year++; } // … } Class name Data (instance variables) Methods
COMP 110: Spring Local/Instance variables Instance variables Declared in a class Can be used anywhere in the class that declares the variable, including inside the class methods Local variables Declared in a method Can only be used inside the method that declares the variable
COMP 110: Spring Simple Example public class Student { public String name; public int year; //... public void printInfo() { String info = name + ": " + year; System.out.println(info); } public void increaseYear() { year++; } public void decreaseYear() { year--; } year and name are instance variables can be used in any method in this class info is a local variable declared inside method printInfo() can only be used inside method printInfo()
COMP 110: Spring Simple Example public class Student { public String name; public int year; //... public void printInfo() { String info = name + : + year; System.out.println(info); } public void increaseYear() { year++; info = My info string; // ERROR!!! } public void decreaseYear() { year--; } The compiler will not recognize the variable info inside of method increaseYear()
COMP 110: Spring More about Local Variables public void printInfo() { String info = name + : + year; System.out.println(info); } public static void main(String[] args) { Student jack = new Student(); jack.name = Jack Smith; jack.major = Computer Science; String info = Hello there!; System.out.println(info); System.out.println(jack.name + is majoring in + jack.major); Student sam = new Student(); sam.name = Samantha Smart; sam.major = Biology; System.out.println(sam.name + is majoring in + sam.major); } Variable info in main method not affected by variable info in printInfo method in class Student
COMP 110: Spring Named Constants in Classes We can declare named constants as instance variables public class Circle { public double radius; //normal instance variable public final double PI = ; //named constant //… }
COMP 110: Spring Methods with Parameters Some methods need data as input in order to perform their function Parameters can be used as (local) variables inside the method public int square(int number) { return number * number; } Parameters go inside parentheses of method header
COMP 110: Spring Calling a Method with Parameters public class Student { public String name; public int year; //... public void setName(String studentName) { name = studentName; } public void setClassYear(int classYear) { year = classYear; }
COMP 110: Spring Calling a Method with Parameters public static void main(String[] args) { Student jack = new Student(); jack.setName(Jack Smith); jack.setClassYear(3); } Arguments
COMP 110: Spring Methods with Multiple Parameters Multiple parameters separated by commas public double getTotal(double price, double tax) { return price + price * tax; }
COMP 110: Spring Method Parameters and Arguments Order, type, and number of arguments must match parameters specified in method heading public String getMessage(int number, char c) { return number + ":" + character; } object.getMessage(7, 'c'); //ok object.getMessage(7, 'c', 7); //error object.getMessage(7.5, 'c'); //error object.getMessage(7, 6); //error += ???
COMP 110: Spring Automatic Type Casting public class SalesComputer { public double getTotal(double price, double tax) { return price + price * tax; } //... SalesComputer sc = new SalesComputer(); double total = sc.getTotal(19.99, Color.RED); double total = sc.getTotal(19.99); double total = sc.getTotal(19.99, 0.065); int price = 50; total = sc.getTotal(price, 0.065); Automatic typecasting
COMP 110: Spring Call-by-Value Parameters in Java are passed by value The value of a variable is passed, not the variable itself Variables passed to a method can never be changed public class Example { public void setVariable(int a) { a = 7; } public static void main(String[] args) { Example example = new Example(); int a = 5; //a == 5 example.setVariable(a); //does not change the value of a //a == 5 } Different Variables!
COMP 110: Spring The Keyword this Within a class definition, this is a name for the receiving object Frequently omitted, but understood to be there public class Student { public int year; public void increaseYear() { this.year++; //use of this not necessary in this case } 19
COMP 110: Spring The Keyword this public static void main(String[] args) { Student jack = new Student(); jack.increaseYear(); Student sam = new Student(); sam.increaseYear(); } public class Student() { public int year; public void increaseYear() { this.year++; } this indicates the receiving object (The object the method was called on)
COMP 110: Spring The Keyword this When is the keyword this useful? When we need to differentiate between local/instance variables w/ the same name public class Student { public int year; public void setClassYear(int year) { this.year = year; }
COMP 110: Spring Calling Methods within Methods Its possible to call methods within other methods If calling a method of the same class, no need to specify receiving object public void method1() { method2(); //no object needed, current object assumed }
COMP 110: Spring The Keyword this Why dont we need to specify an object when calling between methods of the same class? Use of this keyword is implied public void method1() { method2(); } public void method1() { this.method2(); } ===
COMP 110: Spring Calling Methods within Methods public class Example { public void method1() { System.out.println(method1!"); method2(); //no object needed, current object assumed System.out.println(done with method2!"); } public void method2() { System.out.println(method2!"); } public static void main(String[] args) { Example example = new Example(); //create object of class Example example.method1(); System.out.println("Finished!"); }
COMP 110: Spring Public vs Private public void increaseYear() public int year; public: there is no restriction on how you can use the method or instance variable
COMP 110: Spring Public vs Private private double gpa; private int year; private: can not directly use the method or instance variables name outside the class
COMP 110: Spring Example public class Student { public int year; private String major; } Student jack = new Student(); jack.year = 1; jack.major = Computer Science; OK, year is public Error!!! major is private
COMP 110: Spring More about Private Hides instance variables and methods inside the class/object Invisible to external users of the class Users cannot access private class members directly Information hiding
COMP 110: Spring Information Hiding A programmer using a method should only need to know what the method does, not how it does it keyboard.nextInt() Information hiding means hiding the details of the code from the programmer
COMP 110: Spring Example: Rectangle public class Rectangle { public int width; public int height; public int area; public void setDimensions(int newWidth, int newHeight) { width = newWidth; height = newHeight; area = width * height; } public int getArea() { return area; }
COMP 110: Spring Example: Rectangle Rectangle box = new Rectangle(); box.setDimensions(10, 5); //calculates area System.out.println(box.getArea()); // Output: 50 box.width = 6; //access instance variable directly System.out.println(box.getArea()); // Output: 50, but wrong answer!
COMP 110: Spring Accessors and Mutators How do you access private instance variables? Accessor methods (a.k.a. get methods, getters) Allow you to look at data in private instance variables Mutator methods (a.k.a. set methods, setters) Allow you to change data in private instance variables
COMP 110: Spring Example: Student public class Student { private String name; private int age; public void setName(String studentName) { name = studentName; } public void setAge(int studentAge) { age = studentAge; } public String getName() { return name; } public int getAge() { return age; } Accessors Mutators
COMP 110: Spring Private Methods Why make methods private? Helper methods that will only be used from inside a class should be private External users have no need to call these methods Encapsulation
COMP 110: Spring Encapsulation Hiding details of a class that are not necessary to understand how objects of the class are used Two parts Interface Implementation
COMP 110: Spring Class Interface A class interface tells programmers all they need to know to use the class in a program A class interface includes Headings for public methods public Return_Type Method_Name(Parameters) Named constants public static final Var_Name = Constant; Comments for using public methods /* This method does the following */
COMP 110: Spring Implementation The implementation of a class consists of the private elements of the class definition Private instance variables and constants private Type Var_Name; Private methods private Return_Type Method_Name() Bodies of public methods public void myMethod() { //this is the implementation }
COMP 110: Spring Encapsulation Implementation should not affect behavior described by interface Two classes can have the same behavior but different implementations
COMP 110: Spring Two Implementations of Rectangle public class Rectangle { private int width; private int height; private int area; public void setDimensions( int newWidth, int newHeight) { width = newWidth; height = newHeight; area = width * height; } public int getArea() { return area; } public class Rectangle { private int width; private int height; public void setDimensions( int newWidth, int newHeight) { width = newWidth; height = newHeight; } public int getArea() { return width * height; }
COMP 110: Spring Encapsulation Implementation: Private instance variables Private constants Private methods Bodies of public methods Interface: Comments Headings of public methods Public named constants Programmer Who Uses the Class: Create objects Call methods
COMP 110: Spring Guidelines Comments before class definition Class header Declare instance variables as private Use get & set methods to access instance variables Declare helper methods as private /**/ for interface comments and // for implementation comments
COMP 110: Spring In-Class Exercise Car - make: String - model: String - year: int - owner: String - location: String + accelerate(double pedalPressure): void + brake(double pedalPressure): void + sell(String newOwner): void + start(): void Turn in for class participation credit
COMP 110: Spring Friday Recitation Bring Laptops (fully charged) Textbook