94
Java for C++ Programmers First Night

Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Embed Size (px)

Citation preview

Page 1: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java for C++ Programmers

First Night

Page 2: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Overview

• First Night– Basics– Classes and Objects

• Second Night– Enumerations– Exceptions– Input/Output– Templates vs. Generics– STL vs. JavaSE API

Page 3: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

First Night Agenda

• Basics – file structure, compilation & execution differences, standard out/err/in, primitive types, constants, functions, strings, reference types, arrays, passing variables, command line arguments, packages – Discussion– Lab exercises

• Break• Classes & Objects – declaration, instantiation, access

modifiers, members, methods, common methods, inheritance, interfaces, javadoc– Discussion– Lab exercises

Page 4: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ File Structure

• We typically have header files (*.h, *.H *.hpp) and a source file (*.c, *.C, *.cpp)

• There is no coloration between the name of the file and the classes (if any) defined within

Page 5: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Example – factorial.H

#ifndef _FACTORIAL_H_#define _FACTORIAL_H_

int factorial(int n);

#endif

Page 6: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Example – factorial.C

#include "factorial.H"

int factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result;}

Page 7: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Example – example1.C

#include <iostream>#include "factorial.H"

using namespace std;

int main(int argc, char** argv) { int n = 4; cout << "factorial(" << n << "): " << factorial(n) << endl; exit(0);}

Page 8: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java File Structure

• No separate header file – all code is in a *.java file– No duplication of method signature in declaration

(*.H) and definition (*.C) to keep in sync– No guarding of files to prevent against multiple

includes

• A file must contain a class of the same name– By convention files/classes start with a capital letter– Enforced consistency

• No code lives outside of any class

Page 9: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Main Signature

• Main signature is a bit different– No return value– Only 1 argument to main – a String array

public static void main(String[] args)

Page 10: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Factorial Examplepublic class Factorial {

public static void main(String[] args) { int n = 4; System.out.print("factorial("); System.out.print(n); System.out.print("): "); System.out.println(factorial(n)); }

static int factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result; }}

Page 11: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Compilation

• Compilation in C++ is done by compiling each of the *.C files, to produce *.o files

• The object files are then linked to create an executable which can be run directly

factorial.H factorial.Cexample1.C

factorial.oexample1.o

a.out

g++ -c factorial.Cg++ -c example1.C

g++ example1.o factorial.o

To run:a.out

Page 12: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Compilation

• In Java, *.java files are compiled into *.class files • These *.class files contain what is known as

“bytecode”– Bytecode does not get run directly– Bytecode is not linked to produce an executable– Instead, this bytecode is interpreted and executed by

another program known as the Java Virtual Machine (JVM)

– Bytecode can be run on any platform having a JVM

Page 13: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Compilation & Execution

• *.java files are compiled using the javac command

• The class files are then executed using the java command– Note no .class specified when

running

Factorial.java

Factorial.class

javac Factorial.java

To run:java Factorial

Page 14: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Standard In/Out/Error

• Like C++, Java automatically creates streams for stdout, stdin and stderr– cout is equivalent to System.out– cerr is equivalent to System.err– cin is equivalent to System.in

• Unlike C++, no imports or includes need to be made to use these streams

Page 15: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Standard Out/Error

• Output is easily done using one of the print methods off of these objects– System.out.print(arg) – prints the arg– If you want a newline (what you would get by

using endl), use the println variant of this function – System.out.println(arg)

• A detailed list of methods available on System.out or System.err can be found at:– http://java.sun.com/javase/6/docs/api/java/io/

PrintStream.html#method_summary

Page 16: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Standard In

• Like C++, Java automatically creates a stream for stdin– cin is equivalent to System.in

• Unfortunately, reading a given type off of System.in is not as easy as using cin in C++

• Typically another class is used in conjunction with System.in to more easily read values off of the stream

Page 17: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Primitive Types

• Like C++, Java has a built-in boolean type– C++ uses the keyword bool, whereas Java

used the keyword boolean– Both use the values true and false– Unlike C++, you cannot assign non-boolean

types into booleans• boolean x = 1 results in a compiler error

Page 18: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Primitive Types

• Like C++, Java defines a character type – Just like C++, Java uses the char keyword to

declare this type– Character literals are defined using single

quotes such as 'a'

Page 19: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Primitive Types

• Integer types are pretty much the same, both provide the following types– A C++ short int is a Java short– A C++ int is a Java int– A C++ long int is a Java long

• There are no unsigned variants in Java• Unlike C++, if you want to assign a higher

precision number into a lower precision container you must explicitly down cast…

int i = 1234567;short s = (short)i;

Page 20: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Primitive Types

• Like C++, Java has both float and double types• The same down casting rules that applied with

integer types applies to doubles and floats also– So if you want to assign a double into a float you must

cast it to be a float

• Additionally, Java assumes that floating point literals are doubles by default– If you want to create a literal you can tack on an “f” to

the literal to declare it of a float type

float f = 1234.5678f;

Page 21: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Constants

• Constants in C++ are typically done in one of two ways…– A #define

– Or, a const declaration

const double PI = 3.14159;

#define PI = 3.14159;

Page 22: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Constants

• Java does not have a traditional pre-processor to do substitutions like C/C++– Thus it uses an approach similar to the const

declaration

• Constants in Java are typically declared to be public static final– Declared inside a class, outside all methods

public static final double PI = 3.14159;

Page 23: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Functions

• C++ allows non-member functions• Java does not allow non-member

functions– All functions in Java are actually methods– Methods may be made static, essentially

making them equivalent to functions

static int factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result;}

Page 24: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Strings

• Java provides a String class much like the string class in the C++ STL– Similarities…

• Can create by simply using a double quoted string• Concatenation is done using the + operator• Length obtained by calling .length() method

– Some notable differences…• No overloaded [i] operator, use the .charAt(i) method instead• Strings in Java are immutable

• For more documentation on Java strings see:– http://java.sun.com/javase/6/docs/api/java/lang/String.

html

Page 25: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Strings

• Since Strings are immutable a new String is created on all operations– Need to be sure to assign result back into

variable, otherwise result of operation is lost

String s = "foo";s = s + "bar" + "baz";s = s.substring(3);System.out.println(s);s = s.replace("b", "B");System.out.println(s);

Page 26: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Reference Types

• The way Java handles reference (non-primitive) types in Java is very different from that of C++

• A reference is kind of like a pointer in C++, but there are some notable differences– All objects are stored in variables are actually

references to objects– No direct access to the underlying memory, including

no pointer arithmetic– References are strongly typed unlike C++, cannot

assign a Date reference into a String reference– Uninitialized references are set to null (lowercase)

Page 27: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Reference Types

• In C++ we can statically create an object like so…

• Or, dynamically create an object like so (and need to remember to free it like so)…

• In Java, we create an object like so…

Foo * fPtr = new Foo();delete fPtr;

Foo f();

Foo f = new Foo();

Page 28: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Reference Types

• If you’re using new, then it’s a reference

• One of the biggest perks about Java’s approach to references deals with freeing objects– You don’t! No more delete statements.

• Java uses a technique called “Garbage Collection” to automatically free memory which is no longer in use

Page 29: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Arrays

• Arrays are allocated using the new keyword– Primitives are initialized to zero– The boolean type is initialized to false– References are initialized to null

• Unlike C++, arrays in Java are objects– The length of an array can be determined by looking

at the array’s .length member (not a method!)

• Like C++, indexing is supported via square brackets – array[i]

Page 30: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Array Allocation

// example declarationsint[] intArray = new int[10];boolean[] boolArray = new boolean[10];

// note [] may appear before of after, // before is the more popular Java conventionString[] strArray1 = new String[10];String strArray2[] = new String[10];

// may alternately use curly brace syntaxString[] strArray3 = {"foo", "bar", "baz"};

Page 31: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Enhanced For Loop

• Java 5 introduced a number of new features to the language – one of those is an enhanced for loop

• This style for loop is known as a “foreach” loop– Popular looping construct in many languages: PHP,

JavaScript, Perl, Python, Ruby, shell, etc…– C++ does not have a built in equivalent

• Typically a foreach loop is used in place of a traditional for loop when we do not care about the index as we are iterating over the collection

Page 32: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Enhanced For Loop

• The general format of this loop in Java is as follows…

• An example…

for(Type item : Collection) { // do something with item}

for(int i = 0; i < array.length; i++) { System.out.println(array[i]);}// becomes...for(String s : array) { System.out.println(s);}

Page 33: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Passing Variables

• Everything in Java is passed by value– Yes, everything – no goofy & or * notation

• Does this mean passing an array of 1,000,000 items creates another huge array?– No! In the case of an array or object, the

variable represents a reference, so the reference is being passed by value

– So, when dealing with objects, we are always passing references (but by value)

Page 34: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Passing Variablespublic class Test { public static void main(String[] args) { int[] array = new int[10]; for(int i = 0; i < array.length; i++) { array[i] = i; } zeroArray(array); // what is in array? } static void zeroArray(int[] array) { for(int i = 0; i < array.length; i++) { array[i] = 0; } }}

Page 35: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Passing Variables

public class Test { public static void main(String[] args) { int[] array = new int[10]; for(int i = 0; i < array.length; i++) { array[i] = i; } zeroArray(array); // what is in array? } static void zeroArray(int[] array) { array = new int[array.length]; }}

Page 36: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Command Line Arguments

• Now that we know that how arrays are passed we can go back make use of command line arguments

• Remember main takes a String array, so we can access that like any other array…

public static void main(String[] args) { for(String s : args) { System.out.println(s); }}

Page 37: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Packages

• Like C++, Java provides a mechanism to organize code

• Packages are similar to namespaces in C++ but have different syntax and conventions

• In Java classes need not be explicitly be under a package, in which case the default package will be used– Though, this practice is discouraged

Page 38: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Namespaces in C++

namespace A { class Foo { // minimal class };}int main(int argc, char** argv){ A::Foo aFoo(); return 0;}

Page 39: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Packages in Java

• To package a class…– The first line in the Java file should be a

package declaration in the following format…

– The class file should be placed in a directory structure matching the package name…

• foo/bar/baz/Foo.java

package foo.bar.baz;

Page 40: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Packaging Conventions

• Typically package names consist of lowercase letters and/or numbers

• Multiple words are usually separated by periods• In the real world most projects use something

called reverse domain name notation– edu.umbc.dhood2.proj1.ClassName

• Use this as another method to group your code into logical chunks

Page 41: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Using a Package

• Using a file in a package is very similar to that of C++– In C++ we might have something like…

– In Java, the syntax is different – we use the import keyword, drop the angle brackets, and the file extension

#include <sys/socket.h>

import java.util.Date;

Page 42: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Exercises

Using Java, create, compile and run…1. A simple “Hello World” program2. A program which takes a single string as a

command line argument prints out whether or not the string is a palindrome

• Palindrome is a word that reads the same backwards as forwards

3. A program which creates an array of 20 integers, fills it with the Fibonacci sequence and prints it out

• Fibonacci[0] = 1, Fibonacci[1] = 1• Fibonacci[n] = Fibonacci[n-2] + Fibonacci[n-1]

Page 43: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Break

Page 44: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Class Declaration#ifndef _DATE_H_#define _DATE_H_

class Date { private: int m_month; int m_day; int m_year; public: Date(int month, int day, int year); int GetMonth() const; int GetDay() const; int GetYear() const; void SetMonth(int month); void SetDay(int day); void SetYear(int year);};

#endif

Page 45: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Class Definition #include "Date.H"

Date::Date(int month, int day, int year) { this->m_month = month; this->m_day = day; this->m_year = year;}

int Date::GetMonth() const { return this->m_month;}

int Date::GetDay() const { return this->m_day;}

int Date::GetYear() const { return this->m_year;}

void Date::SetMonth(int month) { this->m_month = month;}

void Date::SetDay(int day) { this->m_month = day;}

void Date::SetYear(int year) { this->m_year = year;}

Page 46: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Differences

• Since Java doesn’t split the declaration and implementation, all code is inline

• No semi-colon at the end of the class declaration

• Access explicitly attached to each method

• this is not a pointer, but a reference, so we use the this. instead of this-> notation

Page 47: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Naming Conventions

• Class name are in UpperCamelCase

• Member names are lowerCamelCase

• Method names are lowerCamelCase

Page 48: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Class Declaration & Definition

public class Date {

private int month; private int day; private int year;

public Date(int month, int day, int year) { this.month = month; this.day = day; this.year = year; }

public int getMonth() { return this.month; }

public int getDay() { return this.day; }

public int getYear() { return this.year; }

public void setMonth(int month) { this.month = month; }

public void setDay(int day) { this.day = day; }

public void setYear(int year) { this.year = year; }

}

Page 49: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Method/Member Access

• Private:– Only accessible from within the class or by

friends

• Protected:– Accessible from within the class, and by

derived classes

• Public:– Accessible by any anyone

Page 50: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Access Modifiers

• Java member access is different from that of C++, some notable differences– No friend classes– Addition of 4th type, default (also known as package private)

ModifierWithin Same Class

Within Same Package

In a SubclassEverything

Else

public Y Y Y Y

protected Y Y Y N

default Y Y N N

private Y N N N

Page 51: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Destructors

• In C++ you can create a destructor which gets invoked when the object goes out of scope or, if dynamically allocated when it is deleted

• Typically destructors free any dynamically allocated memory into the date structure

Class::~Class() { // delete allocated memory}

Page 52: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java “Destructor”

• Since Java does garbage collection, there typically is not a need to manually free allocated memory

• When the garbage collector runs, it will invoke a finalize method on classes it collects– No guarantee that this is called when object

goes out of scope – up to the garbage collector as to when it should get called

– This is seldom used in most Java applications

Page 53: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Operator Overloading

• Unlike C++, Java does not allow us to define overloaded operators for classes– Notable exceptions being the built in String (+

operator) and array ([ ] operator) types

• There are, conventions to achieve the same effect in Java for common operations

Page 54: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Outputting an Object in C++

• If we want to output an object in C++ many people will implement an operator<<

// function ostream& operator << (ostream& os, const Date& d) { os << d.GetMonth() << "/" << d.GetDay() << "/" << d.GetYear(); return os;}

// invocationDate d(1,20,2009);cout << d << endl;

Page 55: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Outputting an Object in Java

• What happens if we try to print an object in Java?

• Output…

• This is not useful – where is it coming from?

Date d = new Date(1,20,2009);System.out.println(d);

Date@1a46e30

Page 56: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Outputting an Object in Java

• As we’ll see shortly, all objects in Java inherit from a base object called Object

• When we call System.out.print() with any object a toString() method is getting called– Object provides a toString() method, though it

is pretty useless as is– Frequently toString() is overridden to provide

a meaningful String representation

Page 57: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Outputting an Object in Java

• Example override for our Date object…

• Invocation…

• Output…

public String toString() { return this.month + "/" + this.day + "/" + this.year;}

Date d = new Date(1,20,2009);System.out.println(d);

1/20/2009

Page 58: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Comparing Objects in C++

• In C++, we frequently override the operator== …

// functionbool Date::operator==(const Date& d) const {return (this->m_month == d.m_month) && (this->m_day == d.m_day) && (this->m_year == d.m_year);}

// invocationDate d1(1,20,2009);Date d2(11,4,2008);if(d1 == d2) { cout << "same" << endl;} else { cout << "different" << endl;}

Page 59: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Comparing Objects in Java

• What happens if we try to compare 2 objects in Java…

• Outputs the following… why?

Date d1 = new Date(1,20,2009);Date d2 = new Date(1,20,2009);if(d1 == d2) { System.out.println("same");} else { System.out.println("different");}

different

Page 60: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Comparing Objects in Java

• The == operator is checking to see if the references are the same (both point to same object)

• In order to check the members, we need to override the equals(Object) method inherited from the Object class…

public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } Date otherDate = (Date) obj; return (this.month == otherDate.month) && (this.day == otherDate.day) && (this.year == otherDate.year);}

Page 61: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Comparing Objects in Java

Invocation of equals method…

Output…

Date d1 = new Date(1,20,2009);Date d2 = new Date(1,20,2009);if(d1.equals(d2)) { System.out.println("same");} else { System.out.println("different");}

same

Page 62: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Object Assignment in C++

• To perform assignment in C++, we typically overload the operator=

// definitionDate& Date::operator=(const Date& rhs) { if(this != &rhs) { this->m_month = rhs.m_month; this->m_day = rhs.m_day; this->m_year = rhs.m_year; } return *this;}

// invocationDate d1(1,20,2009);Date d2 = d1;

Page 63: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Object Assignment in Java

• Like comparison, the default behavior in Java is to deal with references– So assigning one variable into another causes both to

point to the same object (shallow copy)

• There is some debate in the Java community on how to handle this– There is a clone() method and interface (we’ll talk

about interfaces later), but it is not without oddities– An alternate approach is to simply use a copy

constructor…

Page 64: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Copy Constructor

• Definition…

• Invocation…

public Date(Date d) { this.month = d.month; this.day = d.day; this.year = d.year;}

Date d1 = new Date(1,20,2009);Date d2 = new Date(d1);

Page 65: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Inheritance

• In C++ we can extend a class, by specifying the superclasses using a “:” notation at the time of declaration

Page 66: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Inheritance

• Base Vehicle class (header)…#ifndef _VEHICLE_H_#define _VEHICLE_H_#include <string>

using namespace std;

class Vehicle { private: string m_make; string m_model; public: Vehicle(string make, string model); string GetMake() const; string GetModel() const;};

#endif

Page 67: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Inheritance

• Base Vehicle class (implementation)…#include "Vehicle.H"#include <iostream>

using namespace std;

Vehicle::Vehicle(string make, string model) { this->m_make = make; this->m_model = model;}

string Vehicle::GetMake() const { return this->m_make;}

string Vehicle::GetModel() const { return this->m_model;}

Page 68: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Inheritance

• A derived Car class (header)…#ifndef _CAR_H_#define _CAR_H_#include "Vehicle.H"#include <string>

using namespace std;

class Car : public Vehicle { private: bool m_fourWheelDrive; public: Car(string make, string model, bool fourWheelDrive); bool HasFourWheelDrive() const ;};

ostream& operator << (ostream& os, const Car& c);

#endif

Page 69: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Inheritance

• A derived Car class (implementation)…#include "Car.H"#include <iostream>

using namespace std;

Car::Car(string make, string model, bool fourWheelDrive): Vehicle(make, model) { this->m_fourWheelDrive = fourWheelDrive;}

bool Car::HasFourWheelDrive() const { return this->m_fourWheelDrive;}

ostream& operator << (ostream& os, const Car& c) { os << (c.HasFourWheelDrive() ? "4WD" : "2WD") << " " << c.GetMake() << " " << c.GetModel(); return os;}

Page 70: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Inheritance

• A derived Airplane class (header)…#ifndef _AIRPLANE_H_#define _AIRPLANE_H_#include "Vehicle.H"#include <string>

using namespace std;

class Airplane : public Vehicle { private: string m_varient; public: Airplane(string make, string model, string varient); string GetVarient() const;};

ostream& operator << (ostream& os, const Airplane& a);

#endif

Page 71: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

C++ Inheritance

• A derived Airplane class (implementation)…#include "Airplane.H"#include <iostream>

using namespace std;

Airplane::Airplane(string make,string model,string varient): Vehicle(make, model){ this->m_varient = varient;}

string Airplane::GetVarient() const { return this->m_varient;}

ostream& operator << (ostream& os, const Airplane& a) { os << a.GetMake() << " " << a.GetModel() << " " << a.GetVarient(); return os;}

Page 72: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Inheritance

• Uses the extend keyword instead of the “:” notation

• See access table for visibility of members in base class

• Use super() to invoke base class constructor

• Use super.method() notation to invoke a method on the base class

Page 73: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Inheritance

• A Vehicle base class…public class Vehicle {

private String make; private String model;

public Vehicle(String make, String model) { this.make = make; this.model = model; }

public String getMake() { return make; }

public String getModel() { return model; }}

Page 74: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Inheritance

• A derived Car class…public class Car extends Vehicle {

private boolean fourWheelDrive;

public Car(String make, String model, boolean fourWheelDrive) { super(make, model); this.fourWheelDrive = fourWheelDrive; }

public boolean hasFourWheelDrive() { return this.fourWheelDrive; }

public String toString() { return (this.fourWheelDrive ? "4WD" : "2WD") + " " + this.getMake() + " " + this.getModel(); }}

Page 75: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Inheritance

• A derived Airplane class…public class Airplane extends Vehicle {

private String varient;

public Airplane(String make, String model, String varient) { super(make, model); this.varient = varient; }

public String getVarient() { return this.varient; }

public String toString() { return this.getMake()+" "+this.getModel()+" "+ this.varient; }}

Page 76: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Inheritance

• Java avoids the “diamond problem” by not permitting multiple inheritance

AirplaneCar

Vehicle

AirplaneCar

Page 77: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Interfaces

• Java provides a construct known as an Interface– Similar to a pure virtual class in C++– Classes in Java “implement” may implement

one or more interfaces– Interfaces typically define a set of operations

(method signatures) which the class must implement

– Interfaces my have static members

Page 78: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Interface

• Why use interfaces?– Interfaces are good for defining the set of

operations a given type of structures should implement

– This is a good practice, as it allows you to swap out/in anything that implements that interface with minimal code changes

– Even more powerful when utilized in conjunction with Java’s version of templates

Page 79: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Interface Example

• A simple Java Interface declaration…

• Note that this is of type interface, not class

public interface Animal { public void talk();}

Page 80: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Interface Example

• A Cat class which implements this interface…

public class Cat implements Animal { public void talk() { System.out.println("Meow"); }}

Page 81: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Interface Example

• A Cat class which implements this interface…

public class Dog implements Animal { public void talk() { System.out.println("Arrrfff!"); }}

Page 82: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Java Interface Example

• The driver class…

• Note that we never have a handle on these animals as a Cat or Dog, just an animal– As long as we call just the Animal interface methods, we can

add as many Animal types as we want and not need to change any code

public class Kennel { public static void main(String[] args) { Animal[] kennel = {new Cat(), new Dog()}; for(Animal a : kennel) { a.talk(); } }}

Page 83: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Comparable Interface

• In C++, we frequently overload one of the comparison operators so that we can sort objects

• Since we can’t define our own operators in Java, it provided an alternate mechanism– There is a Comparable interface that you can

choose to implement which allows many of the built in functions in the Java APIs to sort your custom objects

Page 84: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Comparable Interface

• Basically the Comparable interface requires that we implement the following method– public int compareTo(Object other);

• The method compareTo must return– A negative number if the calling object "comes before"

the parameter other– A zero if the calling object "equals" the parameter

other– A positive number if the calling object "comes after"

the parameter other

Page 85: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Example Comparable Class

import java.util.Arrays;

public class Date implements Comparable {

private int month; private int day; private int year;

public Date(int month, int day, int year) { this.month = month; this.day = day; this.year = year; } public String toString() { return this.month + "/" + this.day + "/" + this.year; }

// continued on next slide

Page 86: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Example Comparable Classpublic int compareTo(Object obj) { if (obj == null || getClass() != obj.getClass()) { System.err.println("Whoops, aborthing"); System.exit(1); } Date date = (Date) obj;

int yearDiff = this.year - date.year; int monthDiff = this.month - date.month; int dayDiff = this.day - date.day;

if(yearDiff != 0) { return yearDiff; } else if (monthDiff != 0) { return monthDiff; } else { return dayDiff; }}

// continued on next slide

Page 87: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Example Comparable Class

public static void main(String[] args) { Date[] dates = { new Date(10,7,2008), new Date(10,15,2008), new Date(9,26,2008), }; Arrays.sort(dates); for(Date d : dates) a{ System.out.println(d); } }}

Page 88: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Date Comparable

• When executed, we get the following output…

9/26/200810/7/200810/15/2008

Page 89: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Javadoc Comments

• Like C++, Java supports both C style (/* */) and C++ style end of line comments

• However, Java introduces another type of comment style know as a Javadoc comment

• These special can be analyzed by the javadoc tool and HTML documentation can be automatically generated

/** * This is a javadoc comment */

Page 90: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Javadoc Tags

• The first sentence in the Javadoc comments is used to provide a high-level description of that member/method/class

• The rest of the paragraph will be shown in a more detailed section in the generated documentation

• Additionally, Javadoc supports tags which identify the attributes of the function such as…– @param name description– @return description

• See the following for more details about javadoc…– http://java.sun.com/j2se/javadoc/writingdoccomments/

Page 91: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

A Javadoc Example/** * This function takes in a Celsius temperature and * returns its Fahrenheit equivalent. * * @param celsius degrees Celsius to be converted * @return the Fahrenheit equivalent * of the Celsius temperature provided */public double celsiusToFahrenheit(double celsius) { return 9.0 / 5 * celsius + 32;}

Page 92: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Javadoc Generation

• To generate the Javadoc generation you need to run the javadoc tool

$ javadoc Test.javaLoading source file Test.java...Constructing Javadoc information...Standard Doclet version 1.6.0_02Building tree for all the packages and classes...Generating Test.html...Generating package-frame.html...Generating package-summary.html...Generating package-tree.html...Generating constant-values.html...Building index for all the packages and classes...Generating overview-tree.html...Generating index-all.html...Generating deprecated-list.html...Building index for all classes...Generating allclasses-frame.html...Generating allclasses-noframe.html...Generating index.html...Generating help-doc.html...Generating stylesheet.css...$

Page 93: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Generated HTML Documentation

• Example method listed in method summary…

• Detailed method description…

Page 94: Java for C++ Programmers First Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates

Exercises

1. Using Java, create, compile and run a program which creates and prints out several Employees (Employee class is derived from Person class)

• Person has an age, first name and last name• An Employee is a Person, with an additional title and

salary2. Once you have things compiling, comment your

classes using javadoc comments, run the javadoc tool and view the results in a browser