Java for C Programmers A Brief Tutorial Overview
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 set. X(int num) { x = num; } public int get. X() { return x; } }
Classes • Fields: member variables – initialized to 0, false, null, or ‘u 000’ • 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 First. Program { public static void main(String [] args) { Foo bar = new Foo(); bar. set. X(5); System. out. println(“X is “ + bar. get. X()); } } • compiling: prompt> javac First. Program. java – javac determines dependencies – above line create the file First. Program. class • running: prompt> java First. Program
Programming Conventions • class naming – capitalize first letter of each word – examples: Foo, Num. Books, This. Is. ATest • field, method, and object naming – capitalize all words except the first – examples: bar, test. Flag, this. Is. Another. Test • 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 array. Test() { 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 – __. to. Compare(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) – __. hash. Code() – __. 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 get. Ch() { return ch; } public boolean equals(Object ch) { return this. char. Value() == ((Foo)ch). get. Ch(). char. Value(); } }
__. equals(Object obj) Method • Example (continued) class Tester { public void static main(Strings [] args) { Character c 1 = new Character(‘a’); Character c 2 = new Character(‘a’); Foo obj 1 = new Foo(c 1); Foo obj 2 = new Foo(c 2); if(obj 1. equals(obj 2)) System. out. println(“Equal”); else System. out. println(“Not Equal”); } }
__. hash. Code 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 x. Pos, y. Pos; public Pixel(int x. Pos, int y. Pos) { this. x. Pos = x. Pos; this. y. Pos = y. Pos; } public int get. XPos() { return x. Pos; } public int get. YPos() { return y. Pos; } }
Inheritance Example (cont. ) class Color. Pixel extends Pixel { private int red, green, blue; public Color. Pixel(int x. Pos, int y. Pos, int red, int green, int blue) { super(x. Pos, y. Pos); this. red = red; this. green = green; this. blue = blue; } public int get. Red() { return red; } public int get. Green() { return green; } public int get. Blue() { 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 Color. Pixel 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 total. Number = 0; private int part. Number; public Product() { part. Number = total. Number; total. Number++; }. . . } • only one copy of total. Number
Static Fields and Methods class Product total. Number = 2 part. Number = 0 object one part. Number = 1 object two
Exceptions • some methods throw exceptions – public void check. It() throws too. Bad. Exception • 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 Except. Test { 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) { Input. Stream. Reader input = new Input. Stream. Reader(System. in); Buffered. Reader in = new Buffered. Reader(input); String line = in. read. Line(); . . . }
Odds and Ends • using string tokens – words in a sentence – String. Tokenizer class • has. More. Tokens() and next. Token() methods • default delimitter is white space (could use anything) – example String line = new String(“Hello there all!”); String. Tokenizer tok = new String. Tokenizer(line); while(tok. has. More. Tokens()) { String tmp = tok. next. Token(); . . . }
Odds and Ends • using string tokens (continued) Hello there all! call to new String. Tokenizer() 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
- Slides: 33