lec14 - Lecture 14 Static methods Static variables(Savitch...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
CS125 Course Notes Lecture 14, Slide 1 Lecture 14 •Static methods •Static variables (Savitch 5.2)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
CS125 Course Notes Lecture 14, Slide 2 Static methods • Belong to the class as a whole, not specific instances (objects) of it. • Can be accessed without instantiating an object of the class type. • All information needed by a static method is available through the parameters or static variables
Background image of page 2
CS125 Course Notes Lecture 14, Slide 3 Static methods continued • Example: public class Calculator { public static int area(int height, int width) { return height*width; } public static int perimeter(int height, int width) { return (height+width)*2; } public void displayArea(int height, int width) { System.out.println(“Area is ”+area(height, width)); } public static int areaSquare(int length) { return area(length, length); } }
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
CS125 Course Notes Lecture 14, Slide 4 Calling a static method • Syntax: ClassName . method ( arguments ); • Example: System.out.println(Calculator.area(10,20); Result: _________ System.out.println(Calculator.area(30,40); Result: _________ System.out.println(Calculator.areaSquare(3); Result: _________ Calculator.displayArea (36,24); Result: _________
Background image of page 4
CS125 Course Notes Lecture 14, Slide 5 Invoking a non-static method in a static one • Since static methods don’t depend on instantiated objects, we can’t refer to any non-static methods or instance variables because they have no value. • In other words, static methods can only call static methods and use static variables.
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
CS125 Course Notes Lecture 14, Slide 6 Static variables • We can also make
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 19

lec14 - Lecture 14 Static methods Static variables(Savitch...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online