Programming with Classes Class Methods & Variables Week 11

32
Programming with Classes Class Methods & Variables Week 11

description

Programming with Classes Class Methods & Variables Week 11. Programming with Objects. CONCEPTS COVERED THIS WEEK. Class Variables Class Methods Running Java outside of BlueJ The main Method. Programming with Classes. CLASS VARIABLES. - PowerPoint PPT Presentation

Transcript of Programming with Classes Class Methods & Variables Week 11

Programming with Classes

Class Methods & Variables

Week 11

Class Variables

Class Methods

Running Java outside of BlueJ

The main Method

Programming with Objects CONCEPTS COVERED THIS WEEK

Programming with Classes CLASS VARIABLES

How can we give each Triangle a unique object number?

Programming with Classes CLASS VARIABLES

How can we give each Triangle a unique object number?

First Idea: Create an int field called number and add 1 to it every time the object constructor is called.

public class Triangle{ // instance variables private int number; ... // Triangle constructor public Triangle() {

... number++; System.out.println("Triangle object " + number + " created"); }

Programming with Classes CLASS VARIABLES

How can we give each Triangle a unique object number?

First Idea: Create an int field called number and add 1 to it every time the object constructor is called.

This does not work as number is an instance variable and therefore re-initialised to zero each time a Triangle is instantiated/created

Programming with Classes CLASS VARIABLES

How can we give each Triangle a unique object number?

Second Idea: We need to create a non-instance count that can be incremented after each new Triangle, and assign its current value to the instance variable number.

This is precisely the purpose behind the creation of so-called static, or Class, variables

Class variables hold state that is shared in common among all objects of the class.

Programming with Classes CLASS VARIABLES

public class Triangle{ // class variable private static int count; // instance variables private int number; ... // Triangle constructor public Triangle() { ... count++; number = count; System.out.println("Triangle object " + number + " created"); }

Programming with Classes CLASS VARIABLES

How can we give each Triangle a unique object number?

Second Idea: Create a static variable called count and add 1 to it each time the constructor is called. Assign the value of count to an instance variable called number in the constructor.

This does work as count is not re-initialised to zero each time a new Triangle object is created

Programming with Classes CLASS VARIABLES

Triangle

count 3

triangle1: Triangle

number 1

height 30

width 40

color “green”

triangle3: Triangle

number 3

height 30

width 40

color “green”

triangle2: Triangle

number 2

height 30

width 40

color “green”

is instance of… is instance of… is instance of…

Programming with Classes CLASS CONSTANTS

For example: In a class that represents bouncing balls it might be useful to declare a constant for the acceleration due to gravity as follows:

private static final int gravity = 3;

There is a Flash demo of bouncing balls at:http://funwithstuff.com/dswmedia/bouncing_ball_v3.html

Constants are class variables that are given a fixed value using the keyword final

Programming with Classes CLASS CONSTANTS

Programming with Classes CLASS METHODS

How can we access the value of a class variable?

We could use an object method but this would require that an object had already been created and we had its reference.

Also, why should we have to create an object to reference a class variable?

It seems rather odd to create a BouncingBall object in order to find the value of gravity that will effect ALL Bouncing Balls.

Programming with Classes CLASS METHODS

How can we access the value of a class variable?

A much better solution would be to have a method that related to the BouncingBall class, rather than to a specific BouncingBall object, as this method has no interest in any specific object’s state.

Such methods are called Class Methods (they are also often referred to as Static Methods), and they are defined as part of a class definition in the same way as object methods.

Programming with Classes CLASS METHODS

public class Triangle{ private static int count; // class variable private int number; // instance variable

// Triangle constructor public Triangle() {

count++; number = count;

}

// get number of Triangle objects created public static int getCount() {

return count; }

BlueJ DemonstrationA look at class methods/variables in the Triangle

class

Programming with Classes CLASS VARIABLES AND METHODS

Class variables hold state that is shared in common among all objects of class

Class methods act on attributes of the whole class through class variables

Class methods can’t access instance variables

Using Java without BlueJ

NumberDisplay

ClockDisplay

project: clock-display X:\projects\wk10\clock-display\

bluej.pkg

bluej.pkh

ClockDisplay.java

ClockDisplay.class

ClockDisplay.ctxt

NumberDisplay.java

NumberDisplay.class

NumberDisplay.ctxt

Programming with BlueJ The BlueJ directory structure

Programming with BlueJ The BlueJ file structure

bluej.pkg contains information about classes in the package. One per package.

bluej.pkh backup of the package file.

Class.java standard Java source code file (text). One per class.

Class.class standard Java bytecode file. One per class

Class.ctxt BlueJ context file. Contains extra information for a class. One per class.

Programming without BlueJ Standard Java Files

Class.java Java source files contain the source code in readable form, as typed in by the programmer.

Class.class Java class files contain byte code (a machine readable version of the class). They are generated by the compiler from the source file.

Where Class is the name of the Java class being defined/created

Programming without BlueJ Standard Java Edit-Compile-Run Cycle

source file

011010

110101

010001

class file011010

110101

1001

10

1

0111

0110110

1

1

editorcompiler

(javac)virtual machine

(java)

Programming without BlueJ Editing Java Source Files

A Java file can be edited using any text editor e.g. Notepad

Careful with using Word as, by default, Word does not save in text format

Be sure to save changes before compiling!

Programming without BlueJ Command Line Invocation

Compilation and execution of Java in JDK are done from a command line.

Windows: DOS shell, i.e. Command Prompt:

Ensure that the directory for the Java compiler (javac) and Java runtime (java) is set in the command path e.g.

set path=C:\Program Files\Java\jdk1.6.0_03\bin

Programming without BlueJ Java Compilation

The name of the JDK compiler is javac

To compile a Java class definition:javac <source name>

javac compiles the source file as well as all other classes the source file depends upon.

Example usage of javac: C:\> cd X:\projects\wk10\ X:\projects\wk10\> javac Triangle.java

Programming without BlueJ Java Compilation (Error Messages)

Example usage of javac:

C:\> CD X:\projects\wk07\ X:\projects\wk07\> javac Triangle.java

Triangle.java:22: ';' expected.

private static int count

^

1 error

X:\projects\wk07\>

The programmer has to open the Java file in the editor, find the line number, fix the error and recompile.

Programming without BlueJ Java Program Execution

Example usage of java:

X:\projects\wk07\> java Triangle

“java” starts the Java virtual machine (JVM).

The named class is loaded and execution is started.

Other classes are loaded as needed.

Only possible if class has been compiled.

How does the system know which of the methods of the class to execute?

Programming without BlueJ Java Program Execution – Problem: Execute What?

Example usage of java:

X:\projects\wk07\> java Triangle

Exception in thread "main" java.lang.NoSuchMethodError: main

Programming without BlueJ Java Program Execution – The Main Method

Example usage of javac:

X:\projects\wk07\> java Triangle

Exception in thread "main" java.lang.NoSuchMethodError: main

The solution: The Java system always executes a class method called main with a specific signature.

Programming without BlueJ Java Program Execution – The Main Method

Fixed signature for the main method:

public static void main(String[] args){ ...}

For this to work, a main method must exist in one (and only one) of the classes being called!

It is possible to place all of an application’s code in a class with just a main method!

But this is absolutely NOT RECOMMENDED!

Programming without BlueJ Java Program Execution – The Main Method

Example of a main method in a class called GameApp:

public static void main(String[] args){ Game game = new Game(); game.play();}

In general the main method should ONLY

– create an object– call the first method

Creating a Java program

• Writing the Java code– Any editor (such as Notepad) can be used

to write a Java program. However, most professional programmers use a software application called an Integrated Development Environment or IDE

–JCreator – http://www.jcreator.com/

Writing with JCreator