Java Methods and Applications CSIS 3701: Advanced Object Oriented Programming
Basic Class Structure package packagename; public class classname { … } Package declaration Class name must be same as name of file Only one class per file All code for class in file (no separate headers and code)
Basic Method Syntax Java completely object oriented by default –All code in context of an object –All code contained in a class definition –Object constructed by another object (or by main application) –Methods then called by that object Other object/main code This object constructs method calls
Basic Method Syntax public returntype methodname(parameters) { … return somevalue; } Mostly same syntax as C/C++ returntype is void if returns nothing public is the encapulation level of the method –public method may be called by any code in any class
Static Methods Can be called without constructing an object public static type methodname(params) { … } –Basic functions (such as square root) –Initial main method –Very simple applications
Applications in Java Must have main method (like C/C++) –Called when application started public static void main(String[] args) { … } Used to pass any command line arguments Must be static so can be called before any object exists yet
Simple “hello world” application public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello world!”); } } Writes string to “standard output” -- DOS window -- Status window in NetBeans
Simple Applications Can use purely static methods to create simple procedural programs in Java