Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java: Getting Started Basic Class Structure

Similar presentations


Presentation on theme: "Java: Getting Started Basic Class Structure"— Presentation transcript:

1 Java: Getting Started Basic Class Structure
Programming & Data Structures

2 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

3 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

4 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

5 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

6 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

7 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

8 Programming & Data Structures
Useful links Programming & Data Structures


Download ppt "Java: Getting Started Basic Class Structure"

Similar presentations


Ads by Google