1 / 33

Java for C++ Programmers

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

tarala
Download Presentation

Java for C++ Programmers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java for C++ Programmers A Brief Tutorial

  2. Overview • Classes and Objects • Simple Program • Constructors • Arrays • Strings • Inheritance and Interfaces • Exceptions

  3. 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; } }

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

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

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

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

  8. 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)

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

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

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

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

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

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

  15. __.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(); } }

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

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

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

  19. 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; } }

  20. 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; } }

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

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

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

  24. Interface • simple example class Tester implements Foo, Bar { . . . } • Foo and Bar are interfaces • Tester must define all methods declared in Foo and Bar

  25. 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)

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

  27. Static Fields and Methods class Product totalNumber = 2 partNumber = 0 partNumber = 1 object one object two

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

  29. 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); } } }

  30. 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(); . . . }

  31. 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(); . . . }

  32. Odds and Ends • using string tokens (continued) • 3 separate strings inside the tokenizer class Hello there all! call to new StringTokenizer() there all! Hello

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

More Related