1 / 40

Overloading, Return Values, API/ Javadoc

Overloading, Return Values, API/ Javadoc. Week 5. Method Call in main(). p ublic class CallExample { public void printout(){ // implementation body } public static void play (){ // implementation body } public int add( int x, int y){ return x+y ; }

alec
Download Presentation

Overloading, Return Values, API/ Javadoc

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. Overloading, Return Values, API/Javadoc Week 5

  2. Method Call in main() public class CallExample{ public void printout(){ // implementation body } public static void play(){ // implementation body } public int add(int x, int y){ return x+y; } public static void main(String[] args){ CallExamplece = new CallExample(); // create an object ce.printout(); // correct printout(); // error CallExample.printout(); // error int res = ce.add(3,5); // correct CallExample.play(); // correct play(); // correct ce.play(); // correct but not recommend } }

  3. public class MethodExample{ public intadd_int(int x, int y){ return x+y; } public double add_double(double x, double y){ return x+y; } public String add_string(String x, String y){ return x+y; } } Can we use the same name for different methods in one class?

  4. Method’s Signature • Components • Name; • How many parameters; • Parameter types; • Does not include the names of the parameters; • Does not include the subroutine’s return type. • E.g.: doTask(double, double, boolean) • Java allows two different methods in the same class to have the same name, provided that their signatures are different.

  5. Overloading • In a java class, no two methods’ signatures are same. • println(int) • println(double) • println(String) • println(char) • println() • Common errors: • intmethodName(double x, String y){ … } • doublemethodName(double x, String y){ … } Error: repeated method definition, their signatures are same

  6. public class OverloadingExample{ public int add(int x, int y){ return x+y; } public double add(double x, double y){ return x+y; } public String add(String x, String y){ return x+y; } public static void main(String[] args){ int x = 3, y = 5; double a = 3.5, b = 4.1 String u = “ids”, v = “201”; OverloadingExampleobj = new OverloadingExample(); intint_val = obj.add(x, y); // int_val = 8 double double_val = obj.add(a, b); // double_val = 7.6 String string_val = obj.add(u, v); // string_val = “ids201” } }

  7. Return Values • return ⟨expression⟩ ; • Usually, the last statement in a method. • Such a return statement can only occur inside the definition of a method. • The type of the ⟨expression⟩ must match the return type that was specified for the method. • Example static doublepythagoras(double x, double y) { // Computes the length of the hypotenuse of a right // triangle, where the sides of the triangle are x and y. return Math.sqrt( x*x + y*y ); } Math.sqrt returns a double value

  8. API / Packages • Application Programming Interface (API) • Methods / subroutines • Java standard packages • To provide larger-scale organization, classes in Java can be grouped into packages • The entire standard Java API is implemented in several packages. • A package can contain both classes and other packages.

  9. A Few Examples

  10. Use Classes From Packages • How do we use these classes and methods in Java standard package? • suppose that you want to declare a variable named basicMathof type java.lang.Math. java.lang.MathbasicMath; basicMath.sqrt(); • Java makes it possible to avoid using the full name of a class by importing the class. import java.lang.Math; Math basicMath; basicMath.sqrt();

  11. Use Classes From Packages • There is a shortcut for importing all the classes from a given package by using wildcard “*”. • import java.awt.*; • The “*” is a wildcard that matches every class in the package. (However, it does not match sub-packages; ) • But when you start importing lots of packages in this way, you have to be careful about one thing: It’s possible for two classes that are in different packages to have the same name.

  12. Example import java.awt.*; Import java.util.*; List list_var; // compiler error; Both contain class List. • Solutions: • Use full name • java.awt.Listawt_list_var; • java.util.Listutil_list_var; • Use import to import the individual classes you need, instead of importing entire packages. (Recommended)

  13. http://docs.oracle.com/javase/6/docs/api/

  14. Every class is actually part of a package. • If a class is not specifically placed in a package, then it is put in something called the default package, which has no name. • Most of classes are stored in jar files.

  15. Customized Packages • File 1: mathpack/add.java package mathpack; public class add() { … } • File 2: mathpack/multiply.java package mathpack; public class multiply(){ … } • File 3: minus.java public class minus(){ … }

  16. Compile Files • Under javadir/mathpack/ type: • javacadd.java • javacmultiply.java • javacminus.java • Under javadir/ type: • javacmathpack/add.java • javacmathpack/multiply.java • javacmathpack/minus.java

  17. JAR File • The basic format of the command for creating a JAR file is: • jar cf jar-file input-file(s) • The options and arguments used in this command are: • The c option indicates that you want to create a JAR file. • The f option indicates that you want the output to go to a file rather than to stdout. • jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required. • The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.

  18. Javadoc • Documenting your codes is very important. • The documentation for most Java APIs is prepared using a system called Javadoc. • Javadoc documentation is prepared from special comments that are placed in the Java source code file, beginning with /** and ending with */. • The Javadoc comment always immediately precedes the thing it is commenting on.

  19. You can have Javadoc comments for subroutines, for member variables, and for classes. • Ignored when the file is compiled. /** * This subroutine prints a 3N+1 sequence to standard output, using * startingValueas the initial value of N. It also prints the number * of terms in the sequence. The value of the parameter, startingValue, * must be a positive integer. */ static void print3NSequence(intstartingValue) { ... }

  20. “javadoc” Tool • Read source codes. • Extract javadoc comments. • Create a set of Web pages containing the comments in a nicely formatted, interlinked form. • Collect public methods, classes, members by default. • If no Javadoc comments, it will construct one, but the comment will contain only basic information such as the name and type of a member variable or the name, return type, and parameter list of a subroutine. This is syntactic information.

  21. “javadoc” Tool • The *’s at the start of each line are optional. The javadoc tool will remove them. • The comment can contain HTML mark-up commands. • E.g. <p> to indicate the start of a new paragraph. • &amp; to represent &. • &lt; to represent <.

  22. Doc Tags • Javadoc comments can include doc tags, which are processed as commands by the javadoc tool. • A doc tag has a name that begins with the character @. • @param ⟨parameter-name⟩ ⟨description-of-parameter⟩ • @return ⟨description-of-return-value⟩ • @throws ⟨exception-class-name⟩ ⟨description-of-exception⟩ • @link ⟨hyper-link-URL⟩ • @see ⟨description-of-see-also⟩

  23. Doc Tags • These tags must be placed at the end of the comment, after any description of the subroutine itself. • The ⟨descriptions⟩ can extend over several lines. The description ends at the next doc tag or at the end of the comment. • A @param tag for every parameter of the subroutine. • A@throws for as many types of exception as you want to document. • A @return tag only for a non-void subroutine.

  24. import java.net.URL; public class DocExample { /** * Returns an Image object that can then be painted on the screen. * The url argument must specify an absolute {@link URL}. The name * argument is a specifier that is relative to the url argument. * <p> * This method always returns immediately, whether or not the * image exists. * * @paramurl an absolute URL giving the base location of the image * @param name the location of the image, relative to the url argument * @return the image at the specified URL * @see Image */ publicintadd(intnumber, Stringname) { try { URL urlObject = new URL(name); return 10*number; } catch (Exception e) { return 0; } } }

  25. Resulting HTML DocExample public int add(int number, String name) Returns an Image object that can then be painted on the screen. The urlargument must specify an absolute URL. The name argument is a specifier that is relative to the urlargument. This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen. Parameters: url- an absolute URL giving the base location of the image. name - the location of the image, relative to the urlargument. Returns: the image at the specified URL. See Also: Image

  26. Short Circuit Logical Operator if( (50>30) && (3/0 > 0)){ System.out.println(“will not be executed, error”); } if((50<30) && (3/0 > 0) ){ System.out.println(“will not be executed, no error”); } False && Whatever  False

  27. Short Circuit Logical Operator if( (50>30) || (3/0 > 0)){ System.out.println(“will not be executed. No error”); } if((50<30) || (3/0 > 0) ){ System.out.println(“will not be executed, error”); } True || Whatever  True

  28. IF-ELSE IF intfirst = (int)(6*Math.random())+1; intsecond = (int)(6*Math.random())+1; intsum = first + second; if(sum > 10){ System.out.println("Excellent"); System.out.printf("Your throws are: %d\t%d\n", first, second); } elseif(sum > 6){ System.out.println("Good"); System.out.printf("Yourthrowsare: %d\t%d\n", first, second); } else{ System.out.println("Do it one more time"); System.out.printf("Yourthrowsare: %d\t%d\n", first, second); }

  29. IF - ELSE intfirst = (int)(6*Math.random())+1; intsecond = (int)(6*Math.random())+1; intsum = first + second; if(sum > 10){ System.out.println("Excellent"); System.out.printf("Your throws are: %d\t%d\n", first, second); } if(sum > 6){ System.out.println("Good"); System.out.printf("Yourthrowsare: %d\t%d\n", first, second); } else{ System.out.println("Do it one more time"); System.out.printf("Yourthrowsare: %d\t%d\n", first, second); }  if(sum > 6 && sum <=10)

  30. int counter =1; booleanisFinish = false; System.out.println("Start Rolling the Dice\n"); do{ System.out.printf("<<<This is your %d time play>>>\n\n",counter); int first = (int)(6*Math.random())+1; int second = (int)(6*Math.random())+1; int sum = first + second; if(sum > 10) System.out.println("Excellent"); elseif(sum > 6) System.out.println("Good"); else System.out.println("Do it one more time"); System.out.println("Do youreallywant to play it again (Y/N)?"); Scanner sc = new Scanner(System.in); Stringanswer = sc.nextLine(); if(answer.equalsIgnoreCase("Y")) isFinish = false; else isFinish = true; counter++; } while(!isFinish); System.out.println("Game done");

  31. Nested For Loop public class NestedLoopExample { public static void main(String[] args) { 1:for(int i=1; i<=5; i++){ 2:System.out.print(i+”:”); 3:for(int j=1; j<=5; j++){ 4:System.out.print(”\t”+j); 5:} 6:System.out.println(); 7:} 8: } } 1: 1 2 3 4 5 2: 1 2 3 4 5 3: 1 2 3 4 5 4: 1 2 3 4 5 5: 1 2 3 4 5

  32. Unlabeled Break public class BreakExample { public static void main(String[] args) { for(int i=1; i<=5; i++){ for(int j=1; j<=5; j++){ if(i%2 == 0) break; else System.out.println("i="+i+"\tj="+j); } System.out.println(“after break”); } } }

  33. Labeled Break public class BreakExample { public static void main(String[] args) { out: for(int i=1; i<=5; i++){ for(int j=1; j<=5; j++){ if(i%2 == 0) break out; else System.out.println("i="+i+"\tj="+j); } } System.out.println(“after break”); } }

  34. Unlabeled Continue public class ContinueExample{ public static void main(String[] args) { for(int i=1; i<=5; i++){ for(int j=1; j<=5; j++){ if(i%2 == 0) continue; System.out.println(”skipped”); else System.out.println("i="+i+"\tj="+j); } } } }

  35. Labeled Continue public class ContinueExample{ public static void main(String[] args) { out: for(int i=1; i<=5; i++){ for(int j=1; j<=5; j++){ if(i%2 == 0) continueout; else System.out.println("i="+i+"\tj="+j); } } } }

  36. Switch public class SwitchExample{ public static void main(String[] args){ for(int x = 1; x<5; x++){ switch(x){ case 1: System.out.print(x); case 2: System.out.print(x); case 3: System.out.print(x); break; case 4: System.out.print(x); default: System.out.print(“+”); } System.out.println(); } } }

  37. Scope of Declaration • The scope of a parameter declaration is the body of the method in which the declaration appears. • The scope of a local-variable declaration is from the point at which the declaration appears to the end of that block. • The scope of a local-variable declaration that appears in the initialization section of a for statement’s header is the body of the for statement and the other expressions in the header. • A method scope is the entire body of the class. This enables non-static methods of a class to use the fields and other methods of the class.

  38. Shadowing • Any block may contain variable declarations. If a local variable or parameter in a method has the same name as a member variable of the class, the member variable is “hidden” until the block terminates execution—this is called shadowing. public class Shadowing{ private intx; public int add(intx, int y){ return x+y; } } Hides

  39. Java Documentation / API • Random number generator • http://docs.oracle.com/javase/7/docs/api/java/util/Random.htm • Random random = new Random(); • int x = random.nextInt(10) + 1;

  40. Publish Your Own JAR • Edit your codes • Compile your codes to class files • Jar your class files into a jar • Publish it and import it when you use it • Build path

More Related