You are on page 1of 4

Java Objects

Last week, we said an object is a collection of data and operations that manipulate that data. Object-Oriented Programming COMS W1007 Introduction to Computer Science Christopher Conway 5 June 2003 In Java, an objects data members are called elds and the operations that manipulate an objects elds are called methods. A class declaration is basically just a list of eld and method denitions.

Packages
A package is a collection of classes. To include a class in a package, we use a package declaration at the beginning of the le. package foo.bar ; public class MyClass { ... } Now, unless we are inside package foo.bar, we must refer to MyClass as foo.bar.MyClass. Warning: The JVM expects to nd foo.bar.MyClass in a directory foo/bar under the CLASSPATH.

The Import Declaration


If we dont want to constantly write foo.bar.MyClass we can us an import declaration. import foo.bar.MyClass ; This tells Java where to nd MyClass when we refer to it by its short name. You can also import every class in a package: import foo.bar.* ;

Access Modiers
Access to an objects elds and methods is governed by access modiers.

But Why?
The ability to hide data allows us to make our code more reusable. If we know that no outside class can change our private data and all data access will be through a dened set of public methods, we can exhaustively test our class and prove that it works correctly. Then we can combine with any other class and be sure it will continue to work correctly. If outside classes cant touch our private data, we dont have to worry about outside code breaking our class.

public - a public eld or method can be seen and accessed by any class. private - a private eld or method can only be seen and accessed inside its own class. protected - a protected eld or method can only be seen and accessed by its own class and related classes.

A eld or method with no access modier can be seen and accessed by any class in the same package.

Class Modiers
The only valid access modier for a class is public. A public class can be seen and used by any other class. Without the public modier, a class can only be used within its own package. There can only be one public class in a le, and the les name must be the same as that class. E.g., public class Foo must be in the le Foo.java.

Accessing Class Members


We access class members using the dot operator. If a eld is an object we can use multiple dot operators to get to its members. System.out.println() ; out is a eld of the class java.lang.System. It is an object of the java.io.PrintStream class. java.io.PrintStream has a method named println. Note: java.lang is a package that is automatically imported into every Java program. It provides the most basic language support classes.

Instance Data
Most class members are associated with an instance of the class.
public class Foo { public int x ; public static void main(String[] args) { Foo a = new Foo() ; Foo b = new Foo() ; a.x = 2 ; b.x = 15 ; /* a.x=2, b.x=15 */ } }

Static Data
Members declared static are associated with the class as a whole. There is only one copy shared between all instances.
public class Foo { public static int x ; public static void main(String[] args) { Foo a = new Foo(), b = new Foo() ; a.x = 2 ; b.x = 15 ; /* a.x=15, b.x=15 */ } }

Final Fields
Fields can be declared final, just like regular variables. A final eld can only be assigned a value once. We usuall dene class constants by declaring them both static and final. public class Color { public static final public static final public static final public static final ... }

Methods
The only way were going to get an object to do anything interesting is to dene operations on the data. A method is a piece of code that tells us about or changes the objects state.
public class Foo { private int x ;

int int int int

RED = 0 ; ORANGE = 1 ; YELLOW = 2 ; BLUE = 3 ;


}

public void setX(int x new) { x = x new ; } public int getX() { return x ; }

Method Declarations
A method declaration denes a methods parameters, its return type and its body (the code). int max(int a, int b) { return a > b ? a : b ; }

Parameters
A methods parameters (or arguments) are values provided by the caller. Parameters look exactly like variables inside the method. int max(int a, int b) { return a > b ? a : b ; }

Return Type
The return type denes what kind of value we can expect when we call the method. The return value is determined by the return statement. When a return statement is encountered, execution of the method stops and the value of its expression is returned to the caller.
int max(int a, int b) { return a > b ? a : b ; } public static void main(String[] args) { int n = max(3,5) ; /* n=5 */ }

Return Type: Void


If a method doesnt need to return a value, we can declare its return type void.
public class Foo { private int x ; void setX(int a) { x = a ; } void printGreeting(String name) { System.out.println("Hello, "+name+".") ; } }

The return Statement


Every method with a non-void return type must have a return statement on every execution path.
int foo(int a) { if( a > 0 ) return 1 ; /* Error: no return if a<=0 */ }

Call-by-Value
Parameters are passed by value: a method operates on a copy of the parameter. Changes to a parameter value arent visible outside the method. void foo(int a) { a = 3 ; } void bar() { int a = 0 ; foo(a) ; /* a=0 */ }

Its usually best to have one return at the end of the method.
int foo(int a) { int result = 0 ; if( a > 0 ) result = 1 ; return result ; }

Parameters vs. Fields


This call-by-value behavior does not apply to elds. They can always be changed by any member method.
public class Foo { private int x ; public void setX(int x new) { x = x new ; } public static void main(String[] args) { Foo f = new Foo() ; f.setX(3) ; /* f.x=3 */ } }

Parameters vs. Fields: 2


It is possible to dene a parameter with the same name as a eld. In this case, the name refers to the more local denition (the parameter).
public class Foo { private int x ; public void setX(int x) { x = x ; /* x is the param! */ } public static void main(String[] args) { Foo f = new Foo() ; f.setX(3) ; /* f.x=? */ } }

The this Keyword


The this keyword is a reference that always points to the current class. We can use it to avoid ambiguity in variable names.
public class Foo { private int x ; public void setX(int x) { this.x = x ; /* this.x is the field */ } public static void main(String[] args) { Foo f = new Foo() ; f.setX(3) ; /* f.x=3 */ } }

Call-by-Value: References
Recall that variables of object types are references. This effects how they behave as parameters.
void f(Foo a) { a = new Foo() ; a.setX(12) ; } void g(Foo a) { a.setX(5) ; } public static void main(String[] args) { Foo a = new Foo(), b = a ; a.setX(2) ; /* a.x=2, b.x=2 */ f(a) ; /* a==b, a.x=2 */ g(a) ; /* a.x=5, b.x=5 */ }

The null Reference


The reference literal null is the value of an uninitialized object variable. If we try to access a member of a null object, we will get an error at runtime. To prevent this, we should check any object that we did not create ourselves (e.g., a parameter) for null before we use it.
public class Foo { private int x ; public static boolean equal(Foo a, Foo b) { if( a==null || b==null ) return false ; return a.x==b.x ; } }

Local Variables
Variables declared inside a method are local to that method (i.e., they have method scope). void f() { int i ; ... } void g() { int i ; /* OK: previous i out of scope */ ... }

Local Variables vs. Fields


A local variable can have the same name as a eld, in which case it hides the eld, just like a parameter. We can still use the this keyword to refer to the eld. public class Foo { private int x ; void f(int a) { int x = 2*a ; if( this.x < x ) this.x = a ; } }

Method Overloading
We can dene two methods with the same name as long as they have different parameter types. Common sense tells us we should only do this if the methods do equivalent things to different types. public static int max(int a, int b) { return a > b ? a : b ; } public static double max(double x, double y) { return x > y ? x : y ; }

Static Methods
A static method is associated with the class as a whole. Static methods cannot use or change any instance data, because they are not part of an instance.
public class Foo { private int x ; private static int y ; public static void f(int a) { x = a ; /* Error: cant change x */ } public static void g(int a) { y = a ; /* OK: y is static */ } }

Static Methods: 2
We often use static methods for general utility methods.
public class Util { public static int max(int a, int b) { return a > b ? a : b ; } public static int pow(int a, int b) { int result=1 ; for( int i=0 ; i < b ; i++ ) result *= a ; } }

The main Method


The main method is declared public, static and void. Because it is static, we often have to create instances of a class inside its own main. Think of main as a little program embedded in the class. It doesnt have special access to any of the classs members; it just uses the class to do something useful, like any other program.

The main Method: 2


Every class can have a main method. If you use ten classes in a program, they may all have main methods. The one that gets executed is from the class you name on the command line. We can use the main method as a way of testing a class, even if the class is a utility class that we dont intend to use as a program. These extra main methods will be ignored when we invoke the program using a different class.

The toString Method


The string concatenation operator (+) converts objects to strings using the toString method. Every object has a default toString method that prints out the classs name and information about its reference value. If you want the toString method to do something more useful, you can dene your own.
public class Foo { private int x ; public String toString() { return "Foo("+x+")" ; } }

Constructors
A constructor is a method that gets called when an object is created using new. We can use the constructor to initialize the elds of the object. A constructor can have as many parameters as necessary, but it cannot have a return type.
public class Foo { private int x ; public Foo(int x) { this.x = x ; } public static void main(String[] args) { Foo a = new Foo(3) ; /* a.x=3 */ } }

The Default Constructor


If we dont dene a constructor for a class, a default constructor with no parameters will be created.
public class Foo { private int x ; public static void main(String[] args) { Foo a = new Foo() ; /* a.x=? */ } }

Default Values
The default constructor assigns the following values to elds, depending on their type. boolean char byte,short,int,long float double reference false 0 0 +0.0F +0.0 null

Constructor Overloading
We can be overloaded constructors, like other methods.
public class Foo { private int x, y ; public Foo(int x) { this.x = x ; y = 5 ; } public Foo(int x, int y) { this.x = x ; this.y = y ; } public static void main(String[] args) { Foo a = new Foo(2) ; /* a.x=2, a.y=5 */ Foo b = new Foo(3,4) ; /* a.x=3, a.y=4 */ } }

Constructor Overloading: 2
We can call one constructor from another using the this keyword. We often use this to supply default arguments to a constructor. A call to another constructor with this can only be the rst statement in the constructor.
public Foo(int x) { this(x,5) ; } public Foo(int x, int y) { this.x = x ; this.y = y ; } public static void main(String[] args) { Foo a = new Foo(2) ; /* a.x=2, a.y=5 */ }

You might also like