Presentation is loading. Please wait.

Presentation is loading. Please wait.

Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables.

Similar presentations


Presentation on theme: "Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables."— Presentation transcript:

1 Writing methods and Java Statements

2 Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables or fields // constructors. with no parameters is Default // methods }

3 Methods public/private returntype name ( /* parameter list */ ) { // statements } public void myMethod( ) { // empty body }

4 Writing our own method: calcVolume public double calcVolume( ) { // NO private in local variables; final for constants final double PI = 3.14159; double volume; // or george. call it anything volume = 4 / 3 * PI * radius * radius * radius; return volume; }

5 Class Details: Methods public double calcVolume( ) { // NO private in local variables; final double PI = 3.14159; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } Java statements inside body, e.g., single = assignment return type double first line signature or header (visible in external view also) return statement Local variable and constant stuff inside curly braces is method body

6 Method vs. InstanceVariable Both have private or public Both have types Both have names instance variables have ‘;’ at end of line/methods do not methods have ( ) (even without parameters); instance variables do not methods have a body; instance variables do not instance variables have memory to hold information; methods do not

7 instance variable (field) vs. Local variable local variables declare in a method; instance variables outside of all methods local variables have the lifetime of the method call local variables and instance variables have type and ‘;’ local variables do NOT have private/public designation when possible, use local variables

8 Writing methods: Java statements must be within a method Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

9 Arithmetic +, /, *, -, % Be careful about integer division Use codepad (Choose view, then codepad) – int answer=30; answer = answer % 4; System.out.println("Answer is " + answer);

10 Compound Assignment assignment: –answer = factor1 * factor2; –answer = answer + newsum; compound assignment –answer += newsum; –answer -= diff; –answer *= product; // e.g., factorial –answer /= digit; // getting rid of digits –answer %= digit; single increment –++count OR count++; // does the same as count += 1 –--count OR count--; // does the same as count -=1

11 Math Problems int x=3; double y=4.0; x + y // this is ok even though different types x / 2 y / 3 x % 2 x % 3 x++ x += 5 x = y; // ok, but truncated x *= 2 // ++, --, +=, etc. work for doubles also

12 Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

13 System.out.println( ) To print out messages to a terminal Can print strings or integers Use + to concatenate/append. Be careful with numbers e.g., –System.out.println("Answer is " + answer); –System.out.println(answer + answer); –System.out.println(“answer is” + answer + answer);

14 Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

15 new, dot notation public void draw() { wall = new Square( ); wall.moveVertical(80); wall.changeSize(100); wall.makeVisible(); //rest of method from Picture class } To create a new object, use new. calls constructor External method call dot notation

16 Most important slide of CS150: Objects, new, dot To declare an object: –NameOfType variableName; To create the object, call its constructor with new –variableName = new NameOfType( ); /* often, caps is class & constructor, lowercase is variable/object. 2 different things. caps is type of dog, lowercase, actual dog */ –name = new Name( ); To do something with the object, use variableName dot methodname –variableName.DoSomething( );

17 New practice on board Declare a variable george of type Picture. Call its constructor. Call george's draw method (use dot notation. to call a method within a class, no dots).

18 Practice Assume that there is a Fraction class that has a write method which prints the Fraction, and two constructors, one that creates some default Fraction value and one that allows two parameters to be passed (e.g., Fraction(3, 4) would create the fraction 3/4). Write a UseFraction class that has two instance variables, both Fractions. Make one the default value and other 4/7. Print both of them out.

19 CNU campus Write two classes, one a Building class and one a Campus class. Buildings have names, number of floors, square feet. Write getName, getFloors, getFeet methods. Campuses have 3 buildings and a name, a print method that prints school name and building info Write a Building class; write a Campus class; Create a campus class. Call its print method

20 Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

21 return statement public double calcVolume( ) { // NO private in local variables; final for constants final double PI = 3.14159; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } type of method is return type to return a value, use ‘return value’; can be calculation

22 public class TestVolume // note: NO ( )s for class { public static void main(String[ ] args) { Sphere sphere = new Sphere( ); double george; george = sphere.calcVolume( ); System.out.println("value is " + george); } Other most important slide: Understanding method calls, object creation

23 Trace on board using debugger

24 return statement public double calcVolume( ) { // NO private in local variables; final for constants final double PI = 3.14159; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } type of method is return type to return a value, use ‘return value’; can be calculation What is the fix?

25 Casting Lesson 1: always test every method Lesson 2: don’t assume answer is correct; check it Fix 1: double volume = 4 / 3; Lesson 3: int / int REALLY is int. Fix 2: volume = (double) 4/3 * PI * radius * radius * radius; Casting should be used when you know the type of the result. int to double ok. double to int, not ok

26 JOptionPane, Section 1.11 To display a message: import javax.swing.JOptionPane; JOptionPane.showMessageDialog( null, // for now, always null "message: I LOVE cpsc150!!!", "Window Title", JOptionPane.INFORMATION_MESSAGE);

27 Reading information in JOptionPane, Section 2.11 String answer = JOptionPane.showInputDialog(null, "What is the weather today", "Weather Predictor", JOptionPane.QUESTION_MESSAGE); System.out.println("The weather is " + answer);

28 Reading information,Section 2.11 converting strings to ints String answer = JOptionPane.showInputDialog(null, "Enter a number", "Window Title", JOptionPane.QUESTION_MESSAGE); System.out.println("Answer is " + answer); // answer*1 error int number = Integer.parseInt(answer); // turns Strings to nbrs System.out.println("Answer is " + number*1);

29 Source Code Review Terms import comments // and /* … */ and /** javadoc here */ public/private –can't see draw; can see changeColor class class name –case sensitive. convention, start with capital fields/instance variables –always private, outside everything except class –specify data type (can be primitive or object) and name –primitive data types: int, double, boolean, char, a few others lowercase –can be initialized; all other statements must be within a method constructor –can have more than one. each must have different signature –always the name of the class. never has a return value

30 Review method (definition) Java statements return type (void if nothing returned) parameters local variable assignment –+, -, *, /, % (result is same as operands) –=, ++, --, +=, -=, *=, /= System.out.println method call new dot notation JOptionPane for reading and writing

31 Accessor Methods Allows outside users to view parts of a class Class has control over what clients see Returns the value being accessed; has no parameters Called getNameOfValueBeingRetrieved public int getNumerator( ) { return numerator; }

32 Accessor Method on Board Write getX for the Circle class

33 Mutator Method Allows clients to set a value in a class Class has control over how that is set returns a void. has parameter that is the new value called setNameOfValueBeingSet public void setDenominator(int d) { if (d != 0) denominator = d; }

34 Mutator Method on Board write setX for Circle Notice not called setXPosition; client shouldn't know name of instance variable


Download ppt "Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables."

Similar presentations


Ads by Google