Você está na página 1de 50

Java Classes

In this lecture...
We will examine: Java classes and their members

in some detail Static variables Static methods The importance of Java classes for Java programming Instance variables and methods Class constructors

The Building Blocks of Java

Classes:

Classes have variables and methods. All methods are defined inside classes a method always belongs to something! Java class library (the Application Programming Interfaces or APIs) - over 2000 classes.

Examples:

GUI, graphics, image, audio

Input/Output (I/O)
Networking

Defining a Class
All the examples done up to now have involved

defining a class! We have either defined a class with a main method, to enable us to test some feature of Java., or we have defined an applet Defining a class is done in a completely standardized way

Subclasses and superclasses


Each class has a superclass and can have

subclasses An example (from biology): The class Mammal could have a superclass Animal and subclasses Lion and Tiger

Basics of a Class
A class has a name A class contains zero or more field members

(variables)
A class contains zero or more method

members (these define some behaviour or actions)


A class also contains one or more
6

constructors (used to create objects of the class type)

Example of a class definition with a main method and one field


public class FieldDemo { public static int x = 4; public static void main(String[] args) { System.out.println("x has value: " + x); } }

The First Line of the Class Definition


This is: public class FieldDemo The first part is a modifier public in this

case
The second part is the keyword class

The third part is the class name FieldDemo

in this case
8

What is a modifier?
This is a keyword used in the definition of some

element of Java which in some way modifies the characteristics of that element, whether it be a class, a variable or a method

Accessibility Modifiers for Classes


public: Accessible everywhere <none> : Accessible within the current class package abstract and final are other modifiers which can be used as well as accessibility modifiers

10

The Class Members


These are the items defined in the block

where the class body is defined (contained between braces curly brackets). Basically the body is everything except the first line of the class. In our previous examples, we have either defined a main() method (for applications) or a paint() method (for applets). So these classes have had just one member a method. Most classes have several method members (as well as field members)
11

The Purpose of the Two Types of Member


The two types of member are used for different

purposes.
Fields store state Methods represent behaviour

12

The Field Members


In our examples, these are declared at the top of

the class body They are basically variables that hold data which record the current state They are sometimes called properties or attributes

13

The Class Example Again looking at the Field Member


public class FieldDemo { public static int x = 4; public static void main(String[] args) { System.out.println("x has value: " + x); } }
14

Output from FieldDemo

15

A Second Example on Fields


public class FieldDemo2 { public static int x = 3, y = 7;

public static void main(String[] args) { System.out.println("x and y = " + (x + y) ); }}

16

Output from FieldDemo2

17

The static keyword


In Java, static means of the class, or belonging to

the class as opposed to belonging to specific objects described by that class

Field Modifiers
static final

18

The Field Accessibility Modifiers


public, protected, private and default (no

19

explicit modifier) public means accessible to everything private means accessible only to the class. In general, it is best to make field variables private, so that they are not accessible outside the class. This is an example of encapsulation protected means accessible to all classes in the same package (packages are discussed later) and subclasses of the class default means accessible to all classes in the same package

The keyword this


When we refer to a static field defined in the

same class, we do not have to actually specify what class the field belongs to it is assumed we are referring to the current class If we want to, we can make the reference explicit. The current class can be referred to as this (the current thing) so we can refer to a field a as this.a

20

There are Several Ways to Initialise Static Fields


Just declare them and they will be given a

default value. Example: int x; Numerical fields have default value of zero, boolean fields have false assigned, char fields have \u0000 assigned (which means the character whose value is coded as 0), reference variables are assigned null Another way is to explicitly assign a value. Example: int x = 99; A third way is to use a static initialisation block
21

Method Members
public class FieldDemo { public static int x = 4; public static void main(String[] args) { System.out.println("x has value: " + x); } }
22

What Are Method Members?


A method is a bit of code representing some

specific action In other languages, methods are sometimes called functions or procedures When a method is called (invoked) data may be passed to it. Some action is performed, and a data item might be returned from the method a returned value

23

Static Methods
We will here look at static methods

These are associated with the class itself (as

opposed to objects described by that class)

24

The First Line of a Static Method


An example:

public static void main(String[] args)


The elements are :

<modifiers> <return type> <method name> <parameter list>


25

Method Accessibility Modifiers


public, protected, private and default (no

explicit modifier) In general, it is best to make methods public , so that they are accessible (exposed) outside the class The exception would be some method which is only used within the class. In this case, it could be made private, to encapsulate it The other 2 accessibility modifiers may be used to control accessibility where we have inheritance

26

The Return Type


This describes the data type of the value a

method returns to its calling method A single value may be returned It may be of any type If no value is to be returned, the return type is described as void The return key word is used to indicate what is returned

27

The Parameter List


This describes the values (parameters or

arguments passed into the method) Examples: public static void main(String [] args)
public static adder (int a, double b)
In the first example, there is one parameter, a

string array ( a group of character strings)


In the second example, there are two

parameters, an int and a double


28

Points about Parameters


Some methods do not have parameters. You still

need the parentheses () You can use any (legal) names you like for the parameters The parameter values are passed in by copying This method of passing data in is called pass by value or call by value

29

Calling (invoking) a method


The method name is used as part of some

expression, with suitable parameters Examples:


myMethod(4, 5); int h = myMethod2(); a = b + myMethod3(5);

30

Method Example 1
public class MethodExample1 { public static void method1 () { System.out.println( "Hello from method1"); } public static void main(String[] args) { this.method1(); }}
31

Output from MethodExample1

32

Promotion of Method Parameters


If a method requiring a double as parameter is

called with an int value, the actual value passed into the method is broadened into a double. There is no problem filling a 64 bit space with a 32 bit int value.
This occurs automatically, and usually does

not give rise to programming problems

33

MethodExample2
public class MethodExample2 { public static void method2 (double x) { System.out.println("Twice " + x + " is " + 2 * x ); } public static void main(String[] args) { method2(6); } }
34

Output from MethodExample2

35

MethodExample3
public class MethodExample3 { public static void method3 (int x) { System.out.println("Twice " + x + " is " + 2 * x ); } public static void main(String[] args) { method3(6.0); } }
36

Result of Attempting to Compile MethodExample3

37

The main() Method


public static void main(String[] args) { // body } This method is called by the JVM to start an application it is the entry point of the application Values can be passed in, and appear as the string array args, accessible by the program
38

Example on passing data into the main method


public class MainExample { public static void main(String[] args) { System.out.println( args [0] + " " + args[1]); } }
39

Running MainExample
We could launch it from the command line

by issuing the command: java MainExample fred jim


Another way is by using Configure User

Tools to set up EditPlus so that when Java is run, the system does a Prompt for arguments. In this case, input fred jim when prompted

40

Output from MainExample

41

The Purpose of Classes


So far we have used a class as something to

hold members (methods and fields) as a way to do simple Java programming In object-oriented programming, a class is used mainly to describe a type of object. Having defined a class, we can use it to construct objects of that type Example: we may describe a Button class, and then create (instantiate) individual Button objects
42

The Importance of Classes in Programming


Classes enable the close (cohesive) association

of field data representing state and methods representing behaviour, all for one entity
An object encapsulates its fields and methods,

exposing only what is to be used by other classes and objects its public interface
Designing a program involves defining classes
43

and the relationships between classes, and creating suitable class packages for deployment

More Examples of Constructor definition


We can define a constructor with parameters

which will assign values to instance variables We might assign default values to some instance variables The following example shows both

44

Example with Two Constructors


public class MyClass2 { int x; // default value will be 0 int y = 5 ; // explicit default value is 5; MyClass2 () { } // use default values

MyClass2 (int a, int b) { x = a; // could use this.a for clarity y = b; } // could use this.b for clarity

45

public void myMethod2 () { System.out.println( x + " " + y); }}

Tester Class for MyClass2


public class TestMyClass2 { public static void main(String[] args) { MyClass2 mc = new MyClass2() ; // use noargs constructor mc.myMethod2(); // call the myMethod method of mc MyClass2 mc2 = new MyClass2(7, 3) ; // use other constructor mc2.myMethod2(); // call the myMethod method of mc }}
46

Output from testMyClass2

47

The no-args Constructor


If the programmer does not define a constructor

with no arguments, one is automatically created) If any other constructor is defined, this automatic no-args constructor is not available If you then want a no-args constructor, you have to define it explicitly

48

Points on Defining Constructors


A constructor is defined in the same way as

an ordinary method, except there is no return type


A constructor is normally defined as public

after all, it should be available for general use


Also, the name of the constructor is the same

as the name of the class


49

Summary
We have looked at Java classes and their

members in some detail Static variables Static methods The importance of classes Instance variables and methods Class constructors Useful classes from the Java APIs

50

Você também pode gostar