A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

46
A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th , 1999

Transcript of A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Page 1: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

A Quick Java Coursepart 1

Michael McDougall

CIS 573

September 27th, 1999

Page 2: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Outline

State the purpose of the discussion– A Java Review/Introduction <- today’s lecture– Java tips & tricks– Programming for GUI Applications

Identify yourself– Michael McDougall– 1 yr programming in Industry in C++– ~8 months programming in Java for Mocha project.– My 1st Powerpoint presentation! Bear with me.

Page 3: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Good References

The Java Programming Language Second Edition. Ken Arnold & James Gosling, Addison Wesley, 1998. Good for basics.

http://www.javasoft.com Java software, news, documentation

http://www.javasoft.com/products/jdk/1.2/docs/index.html Documentation for the vast libraries.

Page 4: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

What is Java?

An island in Indonesia (beyond the scope of this lecture).

A programming language. Imperative (like C or Pascal). Object Oriented (like C++) Goal: Portable and Safe (unlike C)

Page 5: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Java Virtual Machine (JVM)

Java gets compiled into bytecode Bytecode is like machine-code but runs on a

Java Virtual Machine (instead of Pentium, Sparc etc.)

Goal: Programs compiled to bytecode will run on any machine that has a JVM program.

Page 6: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

JVM Continued

C file

Java file

gcc

javac

machine code

bytecode

runs onPentium Chip

runs on JVM

runson

compiler compil

erFASTER

Page 7: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

How to use Java - Preliminary

Make sure ‘javac’ and ‘java’ are available on whatever system you are using.

On gradient or saul you should set your path to include /pkg/java-1.2.2/bin/

Page 8: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

How to use Java

Write a program and save it in a ‘.java’ file. (tip: emacs has a nice Java mode)

Example: MyProgram.java Compile by typing:

%javac MyProgram.java Run the program:

%java MyProgram

Page 9: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Example 1: MyProgram.java

class MyProgram {

public static void main(String[] arg) {

String message = "Hello!";

System.out.println(message);

}

}

Page 10: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Example 1 cont.

C:\School\cis573>javac MyProgram.java

C:\School\cis573>java MyProgram

Hello!

C:\School\cis573>

Page 11: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Variables

Variables are similar to C variables Examples:

int x = 3; // integer with initial valueint y; // integer, no initial valueboolean b = true;

y = x + x;if (b) {

y = 5;}

Page 12: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Arrays

Java has arrays which are similar to arrays in C.

Indexes begin at 0

int[] intArr = new int[2];intArr[0] = 3;intArr[1] = 5 + intArr[0];String[] names = new String[100];names[45] = “Software”;

Page 13: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Loops and Ifs

The syntax for control flow is similar to C.if (x==y) {...}

if (x==y) {...} else {...}

while (x!=y) {...}

for (int i=0; i < 50 ; i++) {...}

do {...} while (x!=y);

Page 14: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Switch

Java has a switch statement which is like the C switch statement.

switch (x) {case 0:

s=“zero”;break;

case 1: case 2:s=“1 or 2”;break;

default:s= “unknown”;

}

Page 15: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Classes

Java programs are structured using Classes Each class contains fields (a set of variables)

and methods (a set of functions). All procedures in Java must belong to a class. A class can control access to its fields and

methods using public and private keywords in the declarations (more later).

An object is an instance of a class.

Page 16: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Class Fields

class Point {public int x;public int y;

} class Prog2 {

public static void main(String[] arg) {Point p = new Point(); //create a Pointp.x = 2;p.y = p.x + 1;

}}

Page 17: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Class Methods

class Foo {

public int twice(int x) {

return (x+x);

}

}

...Foo f = new Foo(); //create a Foo objectint count = f.twice(5); //set count to 10

//using f’s methods...

Page 18: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Subclasses

Classes can be extended by another class. If a class B extends a class A then we say that

B is a subclass of A. A is the superclass of B. A subclass can be used wherever the class

can be used. The subclass inherits the fields and methods of

the superclass (well, some of them).

Page 19: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Subclasses example 1

Class Point {

public int x;

public int y;

} Class BoolPoint extends Point {

public boolean b;

}

Page 20: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Subclasses example 2

...BoolPoint boolP = new BoolPoint();boolP.b = true; //we can use the b fieldboolP.x = 5; //AND the x & y fieldsboolP.y = 7;...

Page 21: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Subclasses example 3

We can use a BoolPoint whenever we use a Point...

...Point p = new BoolPoint();p.x = 4;p.y = 8;...

Page 22: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Subclasses example 4

But we can’t use a Point in place of a BoolPoint (it has no ‘boolean b’ field).

...BoolPoint boolP = new Point();

// BAD - will not compile...

Page 23: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Overriding methods

If a subclass has a method with the same name as a method in the super class then the subclass method is the one that gets executed.

We say that the subclass method overrides the super class method.

Page 24: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Overriding: example

class A {public String getName() {

return “A!”;}

}

class B extends A {public String getName() {

return “B!”;}

}

Page 25: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Overriding example cont.

A a = new A(); //create an A objectSystem.out.print(a.getName()); //Prints “A!”

a = new B(); //create a B objectSystem.out.print(a.getName()); //Prints “B!”

Page 26: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

The Object Class

In fact, all Java classes are subclasses of a special class called Object.

The Object class contains some simple methods like clone(), equals() and toString().

Page 27: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Subclasses are nice

Subclasses allow you to add functionality to pre-existing code without copying it or modifying the original code.

Subclasses allow a limited form of polymorphism.

public genericPrint(Object arg) {String msg = arg.toString();System.out.print(msg);

}

Page 28: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Hiding Methods and Fields

Access to fields and methods can be restricted by using private and protected declarations.

Allows classes to be treated as ‘black-boxes’; the messy details of a class’ implementation is hidden.

Page 29: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Public, Private, Protected

public - visible to all classes protected - visible to all subclasses, hidden

from other classes private - hidden from all other classes. Good Style: never set fields to be public;

always require the programmer to call a method to access data in a class.

Page 30: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Public, Private, Protected example

class List {public void insert(int i) { ... };private void setNewCell(Cell c) {...};protected int getSize() { ... };

}

class ExtList extends List {public void foo() {

insert(3); //OKsetNewCell(c); //not allowedint x = getSize(); //OK

}}

Page 31: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Public, Private, Protected example continued

Class Prog5 {public static main() {

List bunch = new List();bunch.insert(3); // OKbunch.insertNewCell(c); //not allowedint i = bunch.getSize(); //not allowed

}}

Page 32: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Constructors

When you create a new object using new you often want to initialize it using particular values.

Constructors are methods that create new objects of a class.

Example: when we create a Point we should be able to set the x and y fields during the creation.

Page 33: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Constructor example

Class Point {public int x; public int y;public Point(int xArg, int yArg) {

x = xArg;y = yArg;

}}

...Point p = new Point(43,21);int sum = p.x + p.y; //sets sum = 64...

Page 34: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Arrays and Classes

You can declare and use arrays of classes just as you would for integers.

...Point[] pointArr = new Point[10];pointArr[0] = new Point(1,5);pointArr[1] = new BoolPoint(4,5); int sum= pointArr[0].x + pointArr[0].y;...

Page 35: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Null

Any class variable can be set to null. An exception gets raised if you try to use a

variable that is null (more on exceptions later).

Point p = new Point(2,5);int sum = p.x + p.y;

p = null;sum = p.x + p.y; // this will raise an exception

Page 36: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Interfaces

An interface is a list of methods and fields A class which implements the interface must

contain all of the methods and fields listed. Interfaces allow a class to have more than one

superclass. Interface types can be used just like class

types; we can use them for variables, arrays, etc.

Page 37: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Interface example

interface PhdStudent {

public Prof getAdvisor();

} Class CISPhdStudent implements PhdStudent {

private Prof myBoss;

public Prof getAdvisor() {

return myBoss;

}

}

Page 38: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Interface example cont

PhdStudent[] phdArr = new PhdStudent[5];

phdArr[2] = new CISPhdStudent();

Prof pr = phdArr[2].getAdvisor();

Page 39: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Why Interfaces?

Q: Why do we bother with interfaces? Why don’t we always extend classes?

A: Sometimes it isn’t appropriate to put all the functionality in one superclass.

Page 40: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Why Interfaces? example

Student

CISStudent

EnglishStudent

CISPhd

Student

CISUndergrad

Student

EnglishPhd

Student

EnglishUndergrad

Student

superclass

subclassPhd

Student

This slide took me 8 hours to draw!

Page 41: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Casting 1

Subclasses have more functionality than their superclasses. What if we want to use that functionality even if we only have an object of the superclass type?

Example: Say we have a Student object and we want to use it as a CISStudent.

Page 42: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Casting 2

In general we can’t force a Student to be a CISStudent (it might be an EnglishStudent), but if we know that a Student object is actually a CISStudent we can cast the Student.

Student s = new CISStudent();

CISStudent cis = (CISStudent) s;

Page 43: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Casting & instanceof

If you try to cast something that can’t be casted (e.g. cast an EnglishStudent to CISStudent) then an exception will be raised (more on exceptions later, I promise).

You can check if an object is of a certain class by using instanceof.

Page 44: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Instanceof example

String getBuilding(Student s) {if (s instanceof CISStudent) {

return “Moore Bldg”;} else if (s instanceof EnglishStudent) {

return “Bennett Hall”;}

}

Page 45: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Instanceof example 2

To avoid getting exceptions when you cast you should check an object using instanceof before you cast:

CISStudent cis;

if (s instanceof CISStudent) {

cis = (CISStudent) s;

}

Page 46: A Quick Java Course part 1 Michael McDougall CIS 573 September 27 th, 1999.

Garbage Collection

Java uses garbage collection for memory management (like ML, Scheme).

Programmer does not have to worry about memory leaks or pointers.

BigStructure b;//BAD in C, OK in Javafor (int i = 0; i < 1000 ; i++) {

b = new BigStructure();}