instance variables do not

Download Report

Transcript instance variables do not

Writing methods and Java
Statements
Java program
import package;
// comments and /* … */ and /** javadoc here */
public class Name
{
// instance variables or fields
// constructors. with no parameters is Default
// methods
}
Methods
public/private returntype name ( /* parameter list */ )
{
// statements
}
public void myMethod( )
{
// empty body
}
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;
}
return
type
double
Class Details: Methods
first line signature or header
(visible in external view also)
public double calcVolume( ) {
Local variable and constant
// NO private in local variables;
final double PI = 3.14159;
double volume;
volume = 4 / 3 * PI * radius * radius * radius;
return volume;
stuff inside curly braces
is method body
}
return
statement
Java statements inside body,
e.g., single = assignment
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
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
Writing methods: Java statements
must be within a method
•
•
•
•
•
•
•
Arithmetic Expressions
Compound Assignment
System.out.println
new
dot notation: external method calls
return
JOptionPane
Arithmetic
• +, /, *, -, %
• Be careful about integer division
• Use codepad (Choose view, then
codepad)
– int answer=30; answer = answer % 4;
System.out.println("Answer is " + answer);
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
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
Writing methods:
More Java statements
•
•
•
•
•
•
•
Arithmetic Expressions
Compound Assignment
System.out.println
new
dot notation: external method calls
return
JOptionPane
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);
Writing methods:
More Java statements
•
•
•
•
•
•
•
Arithmetic Expressions
Compound Assignment
System.out.println
new
dot notation: external method calls
return
JOptionPane
new, dot notation
public void draw()
{
To create a new object,
use new. calls
constructor
wall = new Square( );
wall.moveVertical(80);
wall.changeSize(100);
wall.makeVisible();
External method call
dot notation
//rest of method from Picture class
}
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( );
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).
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.
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
Writing methods:
More Java statements
•
•
•
•
•
•
•
Arithmetic Expressions
Compound Assignment
System.out.println
new
dot notation: external method calls
return
JOptionPane
return statement
public double calcVolume( )
type of method is
{
return type
// NO private in local variables; final for constants
final double PI = 3.14159;
double volume;
volume = 4 / 3 * PI * radius * radius * radius;
return volume;
}
to return a value, use ‘return
value’; can be calculation
Other most important slide:
Understanding method calls, object creation
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);
}
Trace
• on board
• using debugger
return statement
public double calcVolume( )
type of method is
{
return type
// NO private in local variables; final for constants
final double PI = 3.14159;
double volume;
volume = 4 / 3 * PI * radius * radius * radius;
return volume;
}
What is the fix?
to return a value, use ‘return
value’; can be calculation
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
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);
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);
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);
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
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