introduction to java for c/c++...

75
Introduction to Java for C/C++ Programmers Kevin Squire Department of Computer Science Naval Postgraduate School

Upload: others

Post on 16-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

Introduction to Java for C/C++ Programmers

Kevin SquireDepartment of Computer Science

Naval Postgraduate School

Page 2: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

2

Homework

Download and install Java 6.0 Eclipse

I’ll introduce Eclipse sometime this week

Page 3: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

3

The First Program

class Hello {

// main: generate some simple output

public static void main (String[] args) {

System.out.println ("Hello, world.");

}

}

// Save as Hello.java

// Compile with “javac Hello.java”

// Run with “java Hello”

Page 4: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

4

The First Program

class CLASSNAME {

public static void main (String[] args) {

STATEMENTS

}

}

Page 5: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

5

Variables and Types

Some types are the same as C

int hour, minute;

float temperature;

Some (e.g., Strings) are (somewhat) new:

String firstName;

String lastName;

Page 6: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

6

Printing Variables

class Hello {

public static void main (String[] args) {

String firstLine;

firstLine = "Hello, again!";

System.out.println (firstLine);

}

}

Page 7: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

7

Operators

Mostly the same

int hour, minute;

hour = 11;

minute = 59;

System.out.print ("Number of minutes since midnight: ");

System.out.println (hour*60 + minute);

System.out.print ("Fraction of the hour that has passed: ");

System.out.println (minute/60);

Page 8: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

8

Operators for Strings

Some new:int i = 5;

String hello = "" + i + " Hello, " + "world.";

puts the following string in the variable hello "5 Hello, world."

Page 9: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

9

Math Methods (Functions)

import static java.lang.Math.sqrt;

double root = sqrt (17.0);

double angle = 1.5;

double height = Math.sin (angle);

double degrees = 90;

double angle = degrees * 2 * Math.PI / 360.0;

int x = (int)Math.round (Math.PI * 20.0);

double x = Math.exp (Math.log (10.0));

Page 10: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

10

static keyword

In addition to (instance) members, a Java class can include static members that are attached to the class rather than instances of the class.

Equivalent to C/C++ functions which are not class methods

Since they are not attached to objects, they do not have access to any particular object’s data members

All Math functions (Math.sin, Math.sqrt, etc.) are static member functions of the Math class.

Page 11: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

11

Defining New Static Methods

Form:public static void NAME ( LIST OF PARAMETERS ) {

STATEMENTS

}

Examplepublic static void newLine () {

System.out.println ("");

}

Page 12: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

12

Class With Only static Methods

class NewLine {

public static void newLine () {

System.out.println ("");

}

public static void threeLine () {

newLine (); newLine (); newLine ();

}

public static void main (String[] args) {

System.out.println ("First line.");

threeLine ();

System.out.println ("Second line.");

}

}

Page 13: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

13

String Objects

Java has two kinds of variables: primitive types objects

Strings are the only object type we've talked about so far

Questions we might ask: “What is the data contained in a String object?” “What are the methods we can invoke on String objects?”

Page 14: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

14

Aside: Java Documentation

All Java documentation is downloadable or available online.

Try: search Google for “java 5.0 String”

Page 15: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

15

Reminder: chars

char fred = ’c’;

if (fred == ’c’) {

System.out.println (fred);

}

Page 16: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

16

String charAt method

The following code:String fruit = "banana";

char letter = fruit.charAt(1);

System.out.println (letter);

yieldsa

Why?

Page 17: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

17

String charAt method

The following code:String fruit = "banana";

char letter = fruit.charAt(1);

System.out.println (letter);

yieldsa

Why? To get the first letter, use

char letter = fruit.charAt(0);

Page 18: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

18

Length

What's wrong with the statements below?

int length = fruit.length();

char last = fruit.charAt (length);

Page 19: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

19

Length

What's wrong with the statements below?

int length = fruit.length();

char last = fruit.charAt (length); Correct version:

int length = fruit.length();

char last = fruit.charAt (length-1);

Page 20: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

20

Indices

String fruit = "banana";

int index = fruit.indexOf(’a’);

int index = fruit.indexOf(’a’, 2); // start at

// position 2

Page 21: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

21

Other Notes on Strings

Strings are immutable Strings are not comparable with ==, >, etc.

Page 22: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

22

Comparing Strings

String name1 = "Alan Turing";

String name2 = "Ada Lovelace";

if (name1.equals (name2)) {

System.out.println ("The names are the same.");

}

int flag = name1.compareTo (name2);

if (flag == 0) {

System.out.println ("The names are the same.");

} else if (flag < 0) {

System.out.println ("name1 comes before name2.");

} else if (flag > 0) {

System.out.println ("name2 comes before name1.");

}

Page 23: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

23

Interesting Objects

Packages Contain built-in Java classes java.lang is available by default (includes all of the

basic parts of the language) Must be imported, e.g.

import java.awt.*;

imports all classes in the java.awt package.

Page 24: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

24

Point Objects

import java.awt.*; // goes at top of file, outside main()

...

Point blank;

blank = new Point (3, 4);

Rectangle box = new Rectangle (0, 0, 100, 200);

// Access coordinate of blank

int x = blank.x;

System.out.println (blank.x + ", " + blank.y);

int distance = blank.x * blank.x + blank.y * blank.y;

Page 25: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

25

Objects as Parameters

public static void printPoint (Point p) {

System.out.println ("(" + p.x + ", " + p.y + ")");

}

// System.out.println(blank) gives: java.awt.Point[x=3,y=4]

public static double distance (Point p1, Point p2) {

double dx = (double)(p2.x - p1.x);

double dy = (double)(p2.y - p1.y);

return Math.sqrt (dx*dx + dy*dy);

}

Page 26: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

26

Objects as Return Types

public static Point findCenter (Rectangle box) {

int x = box.x + box.width/2;

int y = box.y + box.height/2;

return new Point (x, y);

}

Page 27: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

27

Objects are Mutable

public static void moveRect (Rectangle box, int dx, int dy) {

box.x = box.x + dx;

box.y = box.y + dy;

}

...

Rectangle box = new Rectangle (0, 0, 100, 200);

moveRect (box, 50, 100);

System.out.println (box);

// yields java.awt.Rectangle[x=50,y=100,width=100,height=200]

Page 28: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

28

Aliasing/References

Rectangle box1 = new Rectangle (0, 0, 100, 200);

Rectangle box2 = box1;

box1 and box2 both refer to the same Rectangle.

Alternatively, we can say that the given Rectangle has two aliases (box1 and box2)

Page 29: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

29

null

When you create an object variable, remember that you are creating a reference to an object. Until you make the variable point to an object, the value of the variable is null. null is a special value in Java (and a Java keyword) that is used to mean “no object.”

The declaration Point blank; is equivalent to the initialization

Point blank = null;

Page 30: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

30

Null Pointer Exceptions

Point blank = null;

int x = blank.x; // NullPointerException

blank.translate (50, 50); // NullPointerException

Page 31: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

31

Garbage Collection

Create a new Point:

Point blank = new Point (3, 4);

Set blank to null:

blank = null;

In C, this would cause a memory leak; the memory allocated in the first statement would be lost until the program exits.

In contrast, Java keeps track of the memory allocated to the object, and reclaims it (deallocates it) when there are no more references to the object

There is therefore no need for “delete” in Java (and it doesn’t exist).

Page 32: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

32

Creating Your Own Classes

Defining classes in Java is slightly different than in C++ By convention, class names (and hence object types) always begin

with a capital letter, which helps distinguish them from primitive types and variable names.

You usually put one class definition in each file, and the name of the file must be the same as the name of the class, with the suffix .java. For example, the Time class is defined in the file named Time.java.

In any program, one class is designated as the startup class. The startup class must contain a method named main, which is where the execution of the program begins. Other classes may have a method named main, but it will not be executed.

Basic differences between Java and C++ class definition are highlighted on the following slides.

Page 33: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

33

C++/Java Class Definition

C++:

class CRectangle {

int width, height;

public:

CRectangle (int, int);

int area () {

return (width*height);

}

};

CRectangle::CRectangle (int a,

int b) {

width = a;

height = b;

}

Java:

public class CRectangle {

private int width, height;

public CRectangle (int a, int b) {

width = a;

height = b;

}

public int area () {

return (width*height);

}

}

Page 34: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

34

C++/Java Class Definition

C++:

class CRectangle {

int width, height;

public:

CRectangle (int, int);

int area () {

return (width*height);

}

}; // Note: ";" required here

CRectangle::CRectangle (int a,

int b) {

width = a;

height = b;

}

Java:

public class CRectangle {

private int width, height;

public CRectangle (int a, int b) {

width = a;

height = b;

}

public int area () {

return (width*height);

}

} // Note: no ";" required here

Page 35: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

35

C++/Java Class Definition

C++:

class CRectangle {

int width, height;

public:

CRectangle (int, int);

int area () {

return (width*height);

}

};

CRectangle::CRectangle (int a,

int b) {

width = a;

height = b;

}

Java:

public class CRectangle {

private int width, height;

public CRectangle (int a, int b) {

width = a;

height = b;

}

public int area () {

return (width*height);

}

}

Page 36: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

36

C++/Java Class Definition

C++:

class CRectangle {

int width, height;

public:

CRectangle (int, int);

int area () {

return (width*height);

}

};

CRectangle::CRectangle (int a,

int b) {

width = a;

height = b;

}

Java:

public class CRectangle {

private int width, height;

public CRectangle (int a, int b) {

width = a;

height = b;

}

public int area () {

return (width*height);

}

}

Page 37: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

37

C++/Java Class Definition

C++:

int main () {

CRectangle rectA (3,4); CRectangle rectB (5,6);

cout << "rectA area: " << rectA.area() << endl; cout << "rectB area: " << rectB.area() << endl;

return 0;}

Java: public class CRectangle { ...

public static void main(String [] args) {

CRectangle rectA = new CRectangle (3,4); CRectangle rectB = new CRectangle (5,6);

System.out.println( "rectA area: " + rectA.area()); System.out.println( "rectB area: " + rectB.area()); }}

Page 38: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

38

C++/Java Class Definition

C++:

int main () {

CRectangle rectA (3,4); CRectangle rectB (5,6);

cout << "rectA area: " << rectA.area() << endl; cout << "rectB area: " << rectB.area() << endl;

return 0;}

Java: public class CRectangle { // main is ... // inside a class def.

public static void main(String [] args) {

CRectangle rectA = new CRectangle (3,4); CRectangle rectB = new CRectangle (5,6);

System.out.println( "rectA area: " + rectA.area()); System.out.println( "rectB area: " + rectB.area()); }}

Page 39: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

39

C++/Java Class Definition

C++:

int main () {

CRectangle rectA (3,4); CRectangle rectB (5,6);

cout << "rectA area: " << rectA.area() << endl; cout << "rectB area: " << rectB.area() << endl;

return 0;}

Java: public class CRectangle { ... // main()’s type is different public static void main(String [] args) {

CRectangle rectA = new CRectangle (3,4); CRectangle rectB = new CRectangle (5,6);

System.out.println( "rectA area: " + rectA.area()); System.out.println( "rectB area: " + rectB.area()); }}

Page 40: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

40

C++/Java Class Definition

Function overloading is the same as C++ Destructors are the same (~ClassName()), but

are not needed as frequently (why?)

Page 41: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

41

Inheritance and Polymorphism

Inheritance and Polymorphism are very similar in Java and C++

To derive a subclass, the notation is class SUBCLASS extends SUPERCLASS {…

The constructor of the superclass is accessed via a call to the function super().

Note that all methods are virtual by default So, if a subclass overrides a method of a parent class, the

“right method” will always be called

Page 42: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

42

Code Example

#include <iostream>using namespace std;

class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};

};

class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}

int area () { return (width * height); }};

In file Polygon.java:

public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}

In file Rectangle.java:

public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }

public int area () { return (width * height); }}

C++: Java:

Page 43: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

43

Code Example

#include <iostream>using namespace std;

class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};

};

class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}

int area () { return (width * height); }};

In file Polygon.java:

public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}

In file Rectangle.java:

public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }

public int area () { return (width * height); }}

C++: Java:

Page 44: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

44

Code Example

#include <iostream>using namespace std;

class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};

};

class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}

int area () { return (width * height); }};

In file Polygon.java:

public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}

In file Rectangle.java:

public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }

public int area () { return (width * height); }}

C++: Java:

Page 45: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

45

Code Example

#include <iostream>using namespace std;

class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};

};

class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}

int area () { return (width * height); }};

In file Polygon.java:

public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}

In file Rectangle.java:

public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }

public int area () { return (width * height); }}

C++: Java:

Page 46: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

46

Code Example (cont.)

In file Triangle.java:

public class Triangle extends Polygon {

public Triangle(int a, int b) {

super(a,b);

}

public int area () {

return (width * height / 2);

}

}

In file PolyTest.java:public class PolyTest {

public static void int main () {

Rectangle rect = new Rectangle(4,5);

Triangle trgl = new Triangle(4,5);

System.out.println(rect.area());

System.out.println(trgl.area());

}

}

class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};

int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}

C++: Java:

Page 47: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

47

Code Example (cont.)

In file Triangle.java:

public class Triangle extends Polygon {

public Triangle(int a, int b) {

super(a,b);

}

public int area () {

return (width * height / 2);

}

}

In file PolyTest.java:public class PolyTest {

public static void int main () {

Rectangle rect = new Rectangle(4,5);

Triangle trgl = new Triangle(4,5);

System.out.println(rect.area());

System.out.println(trgl.area());

}

}

class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};

int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}

C++: Java:

Page 48: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

48

Code Example (cont.)

In file Triangle.java:

public class Triangle extends Polygon {

public Triangle(int a, int b) {

super(a,b);

}

public int area () {

return (width * height / 2);

}

}

In file PolyTest.java:public class PolyTest {

public static void int main () {

Rectangle rect = new Rectangle(4,5);

Triangle trgl = new Triangle(4,5);

System.out.println(rect.area());

System.out.println(trgl.area());

}

}

class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};

int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}

C++: Java:

Page 49: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

49

Polymorphism Example (cont.)

In file Triangle.java:

public class Triangle extends Polygon {

public Triangle(int a, int b) {

super(a,b);

}

public int area () {

return (width * height / 2);

}

}

In file PolyTest.java:public class PolyTest {

public static void int main () {

Polygon rect = new Rectangle(4,5);

Polygon trgl = new Triangle(4,5);

System.out.println(rect.area());

System.out.println(trgl.area());

}

}

class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};

int main () { CPolygon *rect = new CRectangle(4,5); CPolygon *trgl = new CTriangle(4,5); cout << rect->area() << endl; cout << trgl->area() << endl; return 0;}

C++: Java:

Page 50: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

50

C++ Pure Virtual Classes = Java Abstract Classes

#include <iostream>using namespace std;

class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() = 0;

};...int main () { CPolygon *rect = new CRectangle(4,5); CPolygon *trgl = new CTriangle(4,5);// illegal//CPolygon *poly = new CPolygon(4,5); cout << rect->area() << endl; cout << trgl->area() << endl;//cout << poly->area() << endl; return 0;}

In file Polygon.java:

public abstract class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public abstract int area();}...In file PolyTest.java:

public class PolyTest {

public static void int main () {

Polygon rect = new Rectangle(4,5);

Polygon trgl = new Triangle(4,5);

// illegal

// Polygon poly = new Polygon(4,5);

System.out.println(rect.area());

System.out.println(trgl.area());

// System.out.println(poly.area());

}

}

C++: Java:

Page 51: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

51

Class Object

In Java, all classes (built-in and user-defined) are subclasses or descendents of class Object.

You’ll notice this fact when using the online Java documentation

Because of this, every class inherits a number of useful standard methods from class Object, including:

toString(), equal(), hashCode()

It is often useful or necessary to override these methods.

Page 52: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

52

Numerical Object Types

• For each primitive type in Java, there is a corresponding Object type

• Sometimes Object types are required when using built-in classes (e.g., ArrayList)

• Easy to convert between the two (just assign one to the other)

• Note on 8-bit types– char is a character type in Java– byte is an 8-bit numerical type in

Java– These are not equivalent

Booleanboolean

Characterchar

Doubledouble

Floatfloat

Longlong

Shortshort

Integerint

Bytebyte

Object TypePrimitive Type

Page 53: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

53

Additional Type Notes

All Java types are signed The following are illegal in Java:

unsigned long bigLong; // not legal in Java

unsigned double salary; // not legal in Java

The boolean type in Java is called boolean (cf. bool in C++)

true and false are NOT equal to 1 and 0, as they are in C++

Casting between boolean and int types is not allowed:

boolean aBool = false; // not legal in Java

int anInt = (int)aBool; // not legal in Java

Page 54: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

54

Java Interfaces An interface in Java is a collection of method

declarations and constants, with no data and no bodies.

We say that a class implements an interface if it implements all of the methods declared in the interface.

In general, interfaces define behaviors we desire in a wide variety of possibly unrelated classes.

Page 55: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

55

Interface Example As an example, consider an interface for objects

that can be sold:

public interface Sellable {

public String description(); public int listPrice(); public int lowestPrice();}

Any class which implements this interface must define these three functions.

Page 56: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

56

Interface Example Here's a class which implements Sellable:

public class Photograph implements Sellable { private String descript; private int price; private boolean color;

public Photograph(String desc, int p, boolean c) { descript = desc; price = p; color = c; }

public String description() { return descript; } public int listPrice() { return price; } public int lowestPrice() { return price/2; } public boolean isColor() { return color; }}

Page 57: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

57

Interface Example Suppose we had another interface, Transportable:

public interface Transportable { /** weight in grams */ public int weight(); /** whether the object is hazardous */ public boolean isHazardous();}

Note that, as before, the interface defines no code, only function prototypes.

Page 58: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

58

Multiple Inheritance We can then create a class which implements both

interfaces. This is called multiple inheritance.

public class BoxedItem implements Sellable, Transportable {

... public String description() { return descript; } public int listPrice() { return price; } public int lowestPrice() { return price/2; } public int weight() { return weight; } public boolean isHazardous() { return haz; } public int insuredValue() { return price*2; } ...}

Page 59: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

59

Using Interfaces When using objects which define interfaces, we

can treat them very much like classes:

Sellable[] itemsForSale = new Sellable[10];

...itemsForSale[0] = new Photograph(“Monterey Bay”, 100, true);itemsForSale[1] = new BoxedItem(“TV”,...);...

System.out.println(itemsForSale[0].description() + “: $” + itemsForSale[0].listPrice() + + “, sale price: ” + itemsForSale[0].lowestPrice();

Page 60: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

60

Pre-defined Java Interfaces

Java has a large number of useful interfaces pre-defined, many of which we'll see throughout the quarter

Some of them include Comparable: allows objects of an implementing

class to be compared and sorted Runnable: used in threads programming Java Collections Framework interfaces, including

List: list of items Queue: FIFO list Map: collection of <key,value> pairs Set: collection of objects Collection: any of the above, and more

Interfaces used in GUI programming

Page 61: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

61

Inheritance versus Interface

The Java interface is used to share common behavior (only method headers) among the instances of different classes.

Inheritance is used to share common code (including both data members and methods) among the instances of related classes.

In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code.

If an entity A is a specialized form of another entity B, then model them by using inheritance. Declare A as a subclass of B.

Page 62: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

62

C++ Templates ≈ Java Generics

Java includes a generics framework, similar to C++ Templates, which allows us to define a class in terms of formal type parameters.

public class Pair<K,V> { ...

We instantiate a class using actual type parameters.

Pair<String,Integer> pair1 =

new Pair<String,Integer>();

Page 63: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

63

public class Pair<K, V> {

private K key;

private V value;

public void set(K k, V v) {

key = k;

value = v;

}

public K getKey() { return key; }

public V getValue() { return value; }

public String toString() {

return "[" + getKey() + ", " + getValue() + "]";

}

Generics Example

Page 64: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

64

public static void main (String[] args) {

// Create a String-Integer Pair

Pair<String,Integer> pair1 = new Pair<String,Integer>();

pair1.set(new String("height"), new Integer(36));

System.out.println(pair1);

// Create a Student-Double Pair

Pair<Student,Double> pair2 = new Pair<Student,Double>();

pair2.set(new Student("A5976","Sue",19), new Double(9.5));

System.out.println(pair2);

}

}

Generics Example

Page 65: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

65

In the previous example, K and V could be instantiated as arbitrary types. We can also restrict their types:

public class Pair2<K extends Person,

V extends Number> {

private K key;

private V value;

...

Generics will be useful for further discussion on lists and other abstract data types (ADTs).

Generics Example

Page 66: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

66

Eclipse First Run Checklist

First run:

1. Select/create a workspace directory (when eclipse starts)

Page 67: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

67

Eclipse First Run Checklist

1. Change formatting to NOT use tab characters Preferences -> Java -> Code Style -> Formatter

For active profile, select “Java Conventions [built-in]”

Page 68: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

68

Eclipse First Run Checklist

Best: edit this profile, rename it to “Java Conventions [spaces only]” and select “Spaces Only” as the Tab policy.

Page 69: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

69

Eclipse First Run Checklist

Make sure JRE is selected Preferences -> Java -> Installed JREs Add a new JRE if necessary

Page 70: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

70

Eclipse First Run Checklist

Make sure JRE is selected Preferences -> Java -> Installed JREs Add a new JRE if necessary

Page 71: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

71

Eclipse Project Checklist

Create a new Java project

Page 72: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

72

Eclipse Project Checklist Type <Your_Last_Name>_Prog_<x>_<Name> for the project name

Select “Use project folder as root for sources and class files. Click Finish.

Page 73: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

73

Eclipse Project Checklist

Right click on the new project, and create a new class

Page 74: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

74

Eclipse Project Checklist

• For the new class, fill in a package name (same as Project, but first letter should be lower case), class name, and select appropriate options at the bottom. Click Finish.

Page 75: Introduction to Java for C/C++ Programmersfaculty.nps.edu/kmsquire/cs3901/section2/notes/JavaForCProg.pdfIn C, this would cause a memory leak; the memory allocated in the first statement

75

Eclipse Project Checklist

Your project should look like this. Finish it up and turn it in!