java for c++ programmers a brief tutorial. overview classes and objects simple program constructors...

33
Java for C++ Programmers A Brief Tutorial

Upload: dinah-lindsey

Post on 17-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Java for C++ Programmers

A Brief Tutorial

Page 2: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Overview

• Classes and Objects

• Simple Program

• Constructors

• Arrays

• Strings

• Inheritance and Interfaces

• Exceptions

Page 3: 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;}

}

Page 4: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 5: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 6: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Simple ProgramClass 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

Page 7: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 8: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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)

Page 9: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 10: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 11: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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++)

Page 12: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 13: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 14: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 15: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

__.equals(Object obj) Method

• by default only true if obj is the same as this

• usually need to override this method

• warning: ==, !=, =

• Exampleclass 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();

}

}

Page 16: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

__.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”);

}

}

Page 17: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

__.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

Page 18: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 19: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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;

}

}

Page 20: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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;

}

}

Page 21: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 22: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Abstract Classabstract 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

Page 23: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 24: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Interface

• simple exampleclass Tester implements Foo, Bar {

. . .

}

• Foo and Bar are interfaces

• Tester must define all methods declared in Foo and Bar

Page 25: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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)

Page 26: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Static Fields and Methods

• simple exampleclass Product {

private static int totalNumber = 0;

private int partNumber;

public Product() {

partNumber = totalNumber;

totalNumber++;

}

. . .

}

• only one copy of totalNumber

Page 27: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Static Fields and Methods

class Product

object one

object two

totalNumber = 2

partNumber = 0 partNumber = 1

Page 28: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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

Page 29: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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);

}

}

}

Page 30: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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();

. . .

}

Page 31: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Odds and Ends

• using string tokens– words in a sentence– StringTokenizer class

• hasMoreTokens() and nextToken() methods• default delimitter is white space (could use anything)

– exampleString line = new String(“Hello there all!”);StringTokenizer tok = new StringTokenizer(line);while(tok.hasMoreTokens()) {

String tmp = tok.nextToken();. . .

}

Page 32: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Odds and Ends

• using string tokens (continued)

• 3 separate strings inside the tokenizer class

Hello there all!

Hello there all!

call to new StringTokenizer()

Page 33: Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

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