Java: Getting Started Basic Class Structure Programming & Data Structures
Everything Starts with a Class public class MyClassName { // some variables; what the class “knows” // some methods; the class's “behaviour” // if this is where your program starts public static void main(String args[ ] ) { // code } Programming & Data Structures
In Eclipse, Classes are found in Packages // MyClassName.java package edu.np.pds.sample; public class MyClassName { // some variables // some methods // if this is where your program starts public static void main(String args[ ]) { // code } Programming & Data Structures
Programming & Data Structures Classes and Objects Classes are “kinds” of things like Employee or Message. Objects are instances of Classes like Andrew Pletch or “Hello, world!”. Objects are always created with the new method. class MyMessage { String contents; public MyMessage(String c) { contents = c; } public String toString() { return “My Message: “ + contents; . . . MyMessage helpMessage = new MyMessage(“Help!!!!”); System.out.println(helpMessage); Programming & Data Structures
Variables are Declared inside of Classes Variables come in two flavours – class variables and instance variables. Class Variables: declared with the reserved word static the value is shared by all instances of the class. Instance Variables: declared without the reserved word static values are specific to a single object. Programming & Data Structures
Methods are Declared inside Classes Methods come in two kinds – class methods and instance methods. Class methods: defined with the reserved word static can be executed with just the class name and not the name of a variable referencing a specific object. Instance methods: defined without the reserved word static can't execute without an actual object exhibiting the behaviour of the method. Programming & Data Structures
Class and Instance Variable Example class MyMessage { static String prompt; String contents; public MyMessage(String c) { contents = c; } static public void setPrompt(String p) { prompt = p; public String toString() { return prompt + contents; . . . MyMessage helloMessage = new MyMessage(“Hello!!!!”); MyMessage.setPrompt(“Message: “); MyMessage goodbyeMessage = new MyMessage (“Good-bye.”); System.out.println(helloMessage); System.out.println(goodbyeMessage); Programming & Data Structures
Programming & Data Structures Useful links http://docstore.mik.ua/orelly/java/exp/ch05_06.htm Programming & Data Structures