1 / 42

Methods and Classes

Methods and Classes. Functions in Java. In Java, every program is a “class” i.e. object type there are no functions outside a class So far, we have only used the main method But we can define as many methods as we like in a single class. Example (Only main). class OnlyMain {

Télécharger la présentation

Methods and 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. Methods and Classes

  2. Functions in Java • In Java, every program is a “class” • i.e. object type • there are no functions outside a class • So far, we have only used the main method • But we can define as many methods as we like in a single class

  3. Example (Only main) class OnlyMain { public static void main(String[] args) { String name = new String(“Joe”); int age = 22; System.out.println(“Name:” + name); System.out.println(“Age:” + age); } }

  4. Example (Several Methods) class SeveralMethods { void printName() { String name = new String(“Joe”); System.out.println(“Name: “ + name); } void printAge() { int age = 22; System.out.println(“Age: “ + age); } public static void main(String[] args) { printName(); printAge(); } }

  5. Example (Methods With Parameters) class MethodsWithParameters { void printName(String name) { System.out.println(“Name: “ + name); } void printAge(int age) { System.out.println(“Age: “ + age); } public static void main(String[] args) { printName(“Joe”); printAge(22); } }

  6. Example (Where Did main Go?) class NoMainMethod { void printName(String name) { System.out.println(“Name: “ + name); } void printAge(int age) { System.out.println(“Age: “ + age); } void printDetails() { printName(“Joe”); printAge(22); } }

  7. Method Declarations • A method declaration specifies the code that will be executed when the method is called • When a method is invoked, flow of control jumps to the method and executes its code • When complete, flow returns to where it was called • Methods may or may not return a value

  8. compute myMethod myMethod(); Method Control Flow • If the called method is in the same class, only the method name is needed

  9. main doIt helpMe obj.doIt(); helpMe(); Method Control Flow • The called method is often part of another class or object

  10. The Dot Operator • The dot operator is used to call the methods of an object • e.g. Scanner sc = new Scanner(System.in); input = sc.nextInt(); • nextInt() is a method defined in the Scanner class • To call nextInt(), you need an object of type Scanner

  11. Basics • syntax: <method defn> ::= <modifiers> <type> <identifier> (<parameters>) {<method body>} • Example: char calc (int num1, int num2, String message){…} • everything preceding {…} is the header • everything inside {…} is the body • code that’s run when it’s called

  12. Example class FunctionTest { public static double negate(double x) { return -x; } public static void main(String[] args) { System.out.println( negate(3.4) + 1 ); } } • Output: -2.4

  13. Method Header • A closer look at message headers: char calc (int num1, int num2, String message) method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter return type

  14. Modifiers • Modifiers are optional parts of the header • These modifiers control access • public – can be called from other classes • private – only be called in the declaring class • protected – later • The static modifier preceding a method means it can be called without an instance • Math.sqrt(9);

  15. Method Body • The message body contains statements: char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing The return expression must be consistent with the return type

  16. The return Statement • The return type of a method indicates the type of value that the method sends back to the calling location • A method that does not return a value has a void return type • return statement specifies the value that will be returned return expression; • Its expression must conform to the return type

  17. char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } Parameters • The actual parameters in the invocation are copied into the formal parameters in the method header ch = obj.calc (25, count, "Hello");

  18. The main Method Revisited public static void main (String[] args) • public – can be called from anywhere • static – it is called without an object • void – does not return a value • String[] args • args is a variable of type String[]

  19. Local Data • Local variables can be declared in a method char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } • The scope of a local variable is the body of the method – it can not be referenced outside

  20. This Will Not Work…. {… char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } int getSum() { return sum; } …}

  21. Neither Will This class FunctionTest { public static boolean method1() { return method2(); } public static boolean method2() { return method1(); } public static void main(String[] args) { if(method1()) System.out.println(“Done!”); } }

  22. String Methods • String objects have many defined methods: • all methods listed in the text • Characters in a string can be accessed by an index • indices start at 0 and increment from left to right • Use length() to get the number of characters • Together these methods are useful for iteratively working through the characters in a String

  23. String Mutability • Once a String is created, neither its value nor length can be changed • we say String objects are immutable • String objects have many defined methods: • all methods listed in the text • Some methods return new String objects, such as substrings • gives the illusion of mutability

  24. Using String Methods public class StringShift { public static void main(String[] args) { String name = new String("aaron"); String shifted = new String(""); for(int count=0;count<name.length();count++) shifted = shifted + (char)(name.charAt(count) + 1); System.out.println(shifted); } } Output: bbspo

  25. Using String Methods (again) public class StringShift { public static void main(String[] args) { String name = new String("aaron"); String shifted = new String(""); for(int count=0;count<name.length();count++) shifted = shifted + (char)(name.charAt(count) + ‘A’ – ‘a’); System.out.println(shifted); } } Output: AARON

  26. The equals Method • Consider: String string1 = new String(“Aaron”); String string2 = new String(“Aaron”); • This doesn’t do what you normally want: if(string1==string2) System.out.println(“equal!”); • Use the equals method: if(string1.equals(string2)) System.out.println(“equal!”);

  27. Class Libraries • Classes in Java can be used to hold code libraries • Methods defined in one class can be used in another through the dot operator • The Java Standard Class Library is part of any Java development environment • includes System, String, Scanner • … and many others

  28. Example: A static Function Library class Quadratic { static private double discrim(double a, double b, double c) { return b*b - 4*a*c; } static public double root1(double a, double b, double c) { return (-b - Math.sqrt(discrim(a,b,c))) / (2*a); } static public double root2(double a, double b, double c) { return (-b + Math.sqrt(discrim(a,b,c))) / (2*a); } } Note: NO MAIN METHOD!

  29. Example continued class QuadTest { public static void main(String[] args) { double a=1, b=-4, c=3; System.out.println( Quadratic.root1(a,b,c) ); System.out.println( Quadratic.root2(a,b,c) ); //System.out.println (Quadratic.discrim(a,b,c); } } • Output: 1.0 3.0

  30. Public/Private Modifiers • root1 and root2 can be called because they are public • they can be called from any other class • discrim can not be called in QuadTest, because it is private • but it is called in Quadratic • Instance variables can also be declared public and private

  31. Packages • The Java library is organized in packages • Some standard packages: • java.lang • java.util • java.applet • You can also define your own packages (but we won’t worry about that now)

  32. The Import Declaration • You can use a class in a package by using the full name • java.util.Scanner • Or you can import the class, and then just use the name • import java.util.Scanner; • Or you can import every class in the package • java.util.*;

  33. The Import Declaration • All of the classes in java.lang are automatically imported • that’s why we don’t import String, Math, etc. • Any other packages must be imported

  34. Two Equivalent Classes class DateTest1 { public static void main(String[] args) { java.util.Date d = new java.util.Date(); System.out.println(d); } } //===================================================== import java.util.Date; class DateTest2 { public static void main(String[] args) { Date d = new Date(); System.out.println(d); } }

  35. Example: The Math class • Part of the java.lang package • Contains various mathematical functions: • square root • exponentiation • trigonometry • All the methods are static

  36. Example: The Random Class • The Random class is part of java.util • It provides methods that generate “pseudorandom” numbers • Performs complicated calculations based on a seed value to generate a stream of apparently random values • good enough for us • “real” randomness is harder to generate

  37. The Monty Hall Problem • Based on TV game show • Given 3 doors, behind one is a million dollars • You pick 1 door • The host opens one of the other doors to show it is not the winner, gives you the option to change doors • Question: Should you change?

  38. Strategy 1: Never Change Your Choice static boolean playGame1() { Random generator = new Random(); int winningdoor = generator.nextInt(3); int chosendoor = generator.nextInt(3); if(winningdoor==chosendoor) return true; else return false; }

  39. Strategy 2: Always Change static boolean playGame2() { Random generator = new Random(); int winningdoor = generator.nextInt(3); int chosendoor = generator.nextInt(3); int openeddoor = getDistinctValue(winningdoor,chosendoor); chosendoor = getDistinctValue(chosendoor,openeddoor); if(winningdoor==chosendoor) return true; else return false; }

  40. A Utility Method (not the nicest…) static int getDistinctValue(int w, int c) { int returnvalue = 4; for (int value=0; value<3;value++) { if(value!=w && value !=c) returnvalue = value; } return returnvalue; }

  41. Putting it Together (in MontyHall.java) public static void main(String[] args) { int count1=0; int count2=0; for(int i=0;i<10000;i++) if(playGame1()) count1++; for(int i=0;i<10000;i++) if(playGame2()) count2++; System.out.println("No-switch strategy wins: " + count1 + " out of 10000"); System.out.println("Switch strategy wins: " + count2 + " out of 10000"); }

  42. Output • Slight variation over runs • Strategy 1 = 3224, Strategy 2 = 6663 • Strategy 1 = 3384, Strategy 2 = 6721 • Strategy 1 = 3437, Strategy 2 = 6663 • …. • Conclusion: Always switching doors is better • This can be proved mathematically too… but with some initial controversy

More Related