javaTutorial
Download
Report
Transcript javaTutorial
Java for C++ Programmers
A Brief Tutorial
Overview
•
•
•
•
•
•
•
Classes and Objects
Simple Program
Constructors
Arrays
Strings
Inheritance and Interfaces
Exceptions
Classes
• Everything is contained in a class
• Simple Example
class Foo {
private int x;
public void setX(int num) {
x = num;
}
public int getX() {
return x;
}
}
Classes
• Fields: member variables
– initialized to 0, false, null, or ‘\u000’
• Methods: member functions
• Accessibility
– private: only local methods
– public: any method
– protected: only local and derived classes
Objects
• All objects are accessed and passed by
reference
– similar to pointers in C/C++
• No explicit control of these “pointers”
• Warning: use of ==, !=, and =
– more on this later
Simple Program
Class FirstProgram {
public static void main(String [] args) {
Foo bar = new Foo();
bar.setX(5);
System.out.println(“X is “ + bar.getX());
}
}
• compiling: prompt> javac FirstProgram.java
– javac determines dependencies
– above line create the file FirstProgram.class
• running:
prompt> java FirstProgram
Programming Conventions
• class naming
– capitalize first letter of each word
– examples: Foo, NumBooks, ThisIsATest
• field, method, and object naming
– capitalize all words except the first
– examples: bar, testFlag, thisIsAnotherTest
• constants naming
– capitalize all letters
– examples: PI, MAX_ELEMENTS
Constructors
• called on object creation (similar to C++) to
do some initial work and/or initialization
• can have multiple constructors
• constructors are always public and always
the same name as the class
• no such thing as a destructor (java uses
garbage collection to clean up memory)
Constructor Example
class Example {
private boolean flag;
public Example() {
flag = true;
}
public Example(boolean flag) {
this.flag = flag;
}
}
• this.___ operator used to access object field
• otherwise, parameter overrides object field
Arrays
• similar to C++ in function
– consecutive blocks of memory (first index is 0)
• different from C++ in key ways
– creation:
int [] grades = new int[25];
– __.length operator: keeps track of array size
– out-of-bounds exception: trying to access data
outside of array bounds generates an exception
Array Example
public void arrayTest() {
int [] grades = new int(25);
for(int i=0; i<grades.length; i++)
array[i] = 0;
}
• access arrays same as in C++
• notice no parenthesis after the .length
• could also make an array of objects (similar to a 2-D array
in C++)
Strings
• standard class in Java
• comparing strings
– __.equals(String st): returns true if equal
– __.toCompare(String st): similar to strcmp
•
•
•
•
warning: using ==, !=, and =
concatenation: use the + operator
string length: use the __.length() method
lots more methods for strings
Inheritance
• lets one class inherit fields and methods
from another class
• use keyword extends to explicitly inherit
another classes public and protected
fields/methods
• can only explicitly extend from one class
• all classes implicitly extend the Object class
Object Class
• an Object object can refer to any object
– similar to void pointer in C/C++
• key methods in Object class
– __.equals(Object obj)
– __.hashCode()
– __.clone()
• above methods inherited by all classes
__.equals(Object obj) Method
•
•
•
•
by default only true if obj is the same as this
usually need to override this method
warning: ==, !=, =
Example
class Foo {
private Character ch;
public Foo(Character ch) {
this.ch = ch;
}
public Character getCh() {
return ch;
}
public boolean equals(Object ch) {
return this.ch.charValue() == ((Foo)ch).getCh().charValue();
}
}
__.equals(Object obj) Method
• Example (continued)
class Tester {
public void static main(Strings [] args) {
Character c1 = new Character(‘a’);
Character c2 = new Character(‘a’);
Foo obj1 = new Foo(c1);
Foo obj2 = new Foo(c2);
if(obj1.equals(obj2))
System.out.println(“Equal”);
else
System.out.println(“Not Equal”);
}
}
__.hashCode and __.clone Methods
• __.hashcode hashes object to an integer
– default usually returns a unique hash
• __.clone returns a copy of object
– default sets all fields to the same as original
• can overide either of these functions
Inheritance
• overriding a method
– must have the same signature as original
– declaring a method final means future derived
classes cannot override the method
• overloading a method
– method has same name but different signature
– they are actually different methods
Inheritance Example
class Pixel {
protected int xPos, yPos;
public Pixel(int xPos, int yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
public int getXPos() {
return xPos;
}
public int getYPos() {
return yPos;
}
}
Inheritance Example (cont.)
class ColorPixel extends Pixel {
private int red, green, blue;
public ColorPixel(int xPos, int yPos, int red, int green, int blue) {
super(xPos, yPos);
this.red = red;
this.green = green;
this.blue = blue;
}
public int getRed() {
return red;
}
public int getGreen() {
return green;
}
public int getBlue() {
return blue;
}
}
Inheritance
• abstract classes and methods
– declaring a class abstract
• must have an abstract method
• class cannot be directly used to create an object
• class must be inherited to be used
– declaring a method abstract
• method must be defined in derived class
Abstract Class
abstract class Pixel {
...
public abstract void refresh();
}
class ColorPixel extends Pixel {
...
public void refresh() {
do some work
}
}
• Note: signature of method in derived class must be
identical to parent declaration of the method
Interface
• basically an abstract class where all
methods are abstract
• cannot use an interface to create an object
• class that uses an interface must implement
all of the interfaces methods
• use the implements keyword
• a class can implement more than one
interface
Interface
• simple example
class Tester implements Foo, Bar {
...
}
• Foo and Bar are interfaces
• Tester must define all methods declared in
Foo and Bar
Static Fields and Methods
• field or methods can be declared static
• only one copy of static field or method per
class (not one per object)
• static methods can only access static fields
and other static methods
• accessed through class name (usually)
Static Fields and Methods
• simple example
class Product {
private static int totalNumber = 0;
private int partNumber;
public Product() {
partNumber = totalNumber;
totalNumber++;
}
...
}
• only one copy of totalNumber
Static Fields and Methods
class Product
totalNumber = 2
partNumber = 0
object one
partNumber = 1
object two
Exceptions
• some methods throw exceptions
– public void checkIt() throws tooBadException
• methods that throw exceptions must be
called from within try block
• usually have a catch block that is only
executed if an exception is thrown
• any block of code can be executed in a try
block
Exception Example
class ExceptTest {
public static void main(String [] args) {
int [] grades = new int(25);
try{
for(int i=0; i<=25; i++)
grades[i] = 100;
} catch(Exception e) {
System.out.println(e);
}
}
}
Odds and Ends
• reading data from users
– more complicated than simple cin
– example
public static void main(String [] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(input);
String line = in.readLine();
...
}
Odds and Ends
• using string tokens
– words in a sentence
– StringTokenizer class
• hasMoreTokens() and nextToken() methods
• default delimitter is white space (could use anything)
– example
String line = new String(“Hello there all!”);
StringTokenizer tok = new StringTokenizer(line);
while(tok.hasMoreTokens()) {
String tmp = tok.nextToken();
...
}
Odds and Ends
• using string tokens (continued)
Hello there all!
call to new StringTokenizer()
Hello
there
all!
• 3 separate strings inside the tokenizer class
Odds and Ends
• utilizing files in a code library
– use the import command
– example
import java.lang.*;
– * indicates to include all files in the library