lecture 2 - classes and objects
Download
Report
Transcript lecture 2 - classes and objects
CSC 205
Java Programming II
Java Review I
Classes and Objects
The StringBuffer Class
StringBuffer objects are mutable
Used for holding strings to be changed, convert
into string objects after the changes
Different set of operations (methods)
append: to substitute for the concatenation +
insert: to insert a character sequence into the middle
of a string
replace: to replace a substring in the
StringBuffer object with a given character
sequence
Defining Your Own Classes
A Java program is a collection of classes
All program modules need to appear in one of these
classes that you define
There is no stand-alone method
Every Java source code should include one of the
following statements
class Identifier …{…}
abstract class Identifier …{…}
interface Identifier …{…}
Types of Classes
A class can be really simple, such as this Dummy
class:
public class Dummy { }
It compiles!
You may even instantiate an instance of it in another
class:
public class DummyDemo {
private Dummy d = new Dummy();
…
}
But it can’t do anything. You don’t want to define
something like it.
Types of Classes (cont’d)
Only one class in your program needs to have a
main method, which serves as the entry point to your
application.
There might be hundreds of classes in your
application!
The signature of the main method is
public static void main(String[] args)
Other classes might not have a main method, which
need to be accessed from other classes.
Some classes might have static methods only, like
the Math class.
Defining A Class
Class and object
A class is a template for all objects of the same type.
An object is an instance of the class that it belongs.
A class usually has
Data fields (or instance variables): what an object of
that class knows
Methods: what an object of that class can do
For information hiding, you should define private data
fields and public methods
Using Objects
You should use the new keyword and one constructor
of the class to instantiate an object
The only exception is the String class
An object may be used in
(both sides of) an assignment statement; or as
An argument
A data field of another class