• No results found

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

N/A
N/A
Protected

Academic year: 2021

Share "Short Introduction to the Concepts of Programming in Java Overview over the most important constructs"

Copied!
23
0
0

Loading.... (view fulltext now)

Full text

(1)

Introduction

to Java

• Short Introduction to the Concepts

of Programming in Java

• Overview over the most important

constructs

OOIS 1998/99 Ulrike Steffens Software Systems Institute

ul. steffens @tu- harburg .de http:// www.sts.tu- harburg .de

Data Types

• Two different kinds of data types – primitive types – reference types

Primitive Types

• boolean • char • int • long
(2)

OOIS-11-98-StWe-Java 3

Reference Types

• Predefined or user-defined Classes • String

• Array

• The values of reference types are not manipulated directly.

• Instead handles (references) to the actual values are used.

a b

0 0

Reference Type Variables

• A variable of a reference type contains a reference to an anonymous object in storage.

Point a,b;

• An uninitialized variable contains a null-reference. • Objects are anonymous.

• They have an immutable identity. • Objects are created at run-time.

(3)

OOIS-11-98-StWe-Java 5 a b 0 0 3 4 a b 0 0 3 4

Binding Reference Type Variables

• Assigning an object to a reference type variable, the

variable gets a reference to the object as new value. • The value of the object does not change

a = new Point(0,0); b = new Point(3,4); • Assigning values of other

variables means assigning the references! a = b

• May be a pitfall, as the object may change

a b 34 3 c a == b a != c

Comparing Objects

• Comparing two reference type variables means comparing the references they contain and, thus, comparing the identity of the referenced objects.

(4)

OOIS-11-98-StWe-Java 7

Comparing the Contents of Objects

• The contents of objects belonging to pre-defined classes can be compared using the method equals. • If you define a class of your own, equals by default

only compares references, as == does.

• => You have to override equals for new defined classes.

Creating New Data Types: class

• Class keyword defines new data type

class ATypeName { /* class body goes here */} ATypeName a = new ATypeName ();

• Fields class DataOnly { int i; float f; boolean b; }

• Each instance of DataOnly gets its own copy of the fields

(5)

OOIS-11-98-StWe-Java 9

Methods, Arguments and Return

Values

• Methods: how you get things done in an object – Traditionally called “functions”

– Can only be defined inside classes

returnType methodName (/*argument list */){ /* method body */

}

• Example method call:

int x = a.f(); // For object a

The Argument List

• Types of the objects to pass in to the method • Name (identifier) to use for each one

• Whenever you seem to be passing objects in Java, you‘re actually passing handles

int size(String s){ return s.length (); }

(6)

OOIS-11-98-StWe-Java 11

Control Flow Statements

if (condition) {...} else {...} • (condition) ? value1: value2

while (condition) {...}

do {...} while (condition)

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

switch(value ){ case (value1): ... ; case (value2): ... ; ... default: ...; }

The “static” Keyword

• Normally each object gets its own data

• What if you want only one piece of data shared between all objects of a class? (“class data”)

class StaticTest { static int i = 47; }

• What if you want a method that can be called for the class, without an object? (“class method”)

class StaticFun {

static void incr () { StaticTest .i++; } }

(7)

OOIS-11-98-StWe-Java 13

Guaranteed Initialization with the

Constructor

class Rock {

Rock() { // This is the constructor System. out.println ("Creating Rock"); }

}

public class SimpleConstructor {

public static void main(String args[]) {

for(int i = 0; i < 10; i++) new Rock();

} }

Nuance

• We can deduce meaning from context “Wash the shirt”

“Wash the car” “Wash the dog”

Not “shirtWash the shirt” “carWash the car” “dogWash the dog”

(8)

OOIS-11-98-StWe-Java 15

Method Overloading

void wash (shirt s) { // ... void wash (car c) { // ... void wash (dog d) { // ...

Unique argument combinations distinguish overloaded methods

Method Overloading

• One word, many meanings: overloaded class Tree {

int height ; Tree () {

System. out.println ("A seedling "); height = 0;

}

Tree (int i) {

System. out.println ("A new Tree , " + i + " feet tall ");

height = i; }

(9)

OOIS-11-98-StWe-Java 17 void info () {

System. out.println ("Tree is " + height + " feet tall ");

}

void info (String s) {

System. out.println (s + ": Tree is “ + height + " feet tall "); }

}

Default Constructor:

Takes no Arguments

• Compiler creates one for you if you write no constructors

class Bird { int i; }

public class DefaultConstructor {

public static void main (String args []) { Bird nc = new Bird (); // default !

(10)

OOIS-11-98-StWe-Java 19

this

: Handle to Current Object

public class Leaf {

private int i = 0; Leaf increment () { i++; return this; } void print () {

System. out.println ("i = " + i); }

public static void main (String args []) { Leaf x = new Leaf ();

x. increment ().increment ().increment ().print (); }

}

this in Constructors

• A very common kind to use this is in constructors to initialize data fields with the constructor's arguments

public class Animal {

private int numberOfLegs ; Animal(int numberOfLegs ) {

this. numberOfLegs = numberOfLegs ; }

(11)

OOIS-11-98-StWe-Java 21

Overloading on Return Values

• Why not also use return values in method overloading?

void f() { // ... int f() { // ...

• Then what would this mean? f();

Member Initialization

void f() { int i; // No initialization i++; }

• Produces compile-time error

• Inside class, primitives are given default values if you don’t specify values

class Data { int i = 999;

(12)

OOIS-11-98-StWe-Java 23

Array Initialization

int a1[]; // this ...

int[] a1; // is the same as this ! • Creates a handle, not the array. Can’t size it. To

create an array of primitives:

int a1[] = { 1, 2, 3, 4, 5 }; • An array of class objects:

Animal a[] = new Animal [20]; // 20 x null System. out.println (a.length + " animals "); for(int i = 0; i < a. length ; i++) {

a[i] = new Animal ((i % 2 + 1) * 2); }

• Bounds checked, length produces size

Array Initialization

• Can also use bracketed list (The size is then fixed at compile-time) Integer[] a = { new Integer(1), new Integer(2), new Integer(3), };

• If you do anything wrong either the compiler will catch it or an exception will be thrown

(13)

OOIS-11-98-StWe-Java 25

Multi-dimensional Arrays

• It is possible to define multi-dimensional arrays in the same way as described.

int[][] a;

• The brackets even may be distributed between type and identifier.

int[] a[];

• Initialization can be done directly

int[][] a = { { 1, 2, 3 }, { 5, 6} };

• It can also be done by nested iterations over the array and its components.

• arrays may not be rectangular

Strings

• Strings are immutable objects of the class String. • String literals are zero, one or more characters

included within double quotes.

• When a binding to a string literal is executed for the first time, a new String object is created.

• If any other bindings to this literal appear, the respective variables will hold reference to the same object.

(14)

OOIS-11-98-StWe-Java 27 "abc" a b c "abc"

String Constructors

• String objects can also be created by calling a constructor.

• String constructors create new objects whenever they are called.

String c = new String(" abc");

• There are several constructors defined for strings.

String Concatenation

• Strings can be concatenated by using +. String c = "A " + "concatenation";

• The concatenation also creates a new String object. • Values of other types can be concatenated to strings,

too.

• They are implicitly converted to String. String n = "Number " + 49;

(15)

OOIS-11-98-StWe-Java 29

Package:

the Library Unit

import java .util .*; import java .util .Vector ; • Managing “name spaces”

– Class members are already hidden inside class – Class names could clash

– Need completely unique name • Compilation units (.java files)

– Name of .java file == name of single public class – Other non-public classes are not visible

– Each class in file gets its own .class file

– Program is a bunch of .class files (no .obj or .lib)

Creating a Library of Classes

package mypackage ;

public class is under the umbrella mypackage

– Client programmer must import mypackage.*;

• Creating unique package names

– Location on disk encoded into package name – Convention: first part of package name is Internet

domain name of class creator (reversed)

(16)

OOIS-11-98-StWe-Java 31

Library Location

C:\DOC\Java\ SomeDirectory \util • CLASSPATH takes care of first part:

CLASSPATH=.;D:\JAVA\LIB;C:\DOC\ JavaT • Programs can be in any directory

import SomeDirectory .util .*; public class LibTest {

public static void main (String args []) { Vector v = new Vector ();

List l = new List(); }

}

• Compiler starts search at CLASSPATH

Java Access Control

Interface Access

Only Accessible Within the class

“Sort of private“

public

private

(17)

OOIS-11-98-StWe-Java 33

“Friendly”

• Default access, has no keyword

• public to other members of the same package, private to anyone outside the package.

• Easy interaction for related classes (that you place in the same package)

• Also referred to as “package access”

public: Interface Access

package c05. dessert ;

public class Cookie { public Cookie () {

System. out.println ("Cookie constructor "); }

void foo () { System. out.println ("foo"); } }

// Separate file : import c05. dessert .*; public class Dinner { public Dinner() {

(18)

OOIS-11-98-StWe-Java 35

private: Can’t Touch That!

class Sundae {

private Sundae () {}

static Sundae makeASundae () { return new Sundae ();

} }

public class IceCream {

public static void main (String args []) { //! Sundae x = new Sundae ();

Sundae x = Sundae .makeASundae (); }

}

protected

• Finer grained, deals with inheritance • Generally: when you need it, you’ll know

(19)

OOIS-11-98-StWe-Java 37

An Object has an Interface

• Object : Characteristics and Behavior

• Object Creation: Light lt = new Light ();

• Message: lt.on();

That‘s programming with objects! Light on() off() brighten() dim() Interface Type name

Inheritance

• Inheritance: Automatically duplicates the interface Line draw() erase() Shape draw() erase() Circle draw() erase() Square draw() erase()
(20)

OOIS-11-98-StWe-Java 39 public class Shape {

public void draw() { /* code drawing a shape */} public void erase() { /* code erasing a shape */} }

public class Circle extends Shape{

public void erase() { /* code erasing a circle */} }

Line Shape

Circle Square ... works with all this objects One piece of code ...

Polymorphism

draw() erase ()

(21)

OOIS-11-98-StWe-Java 41

An Amazing Trick

void doStuff (Shape s) { s.erase ();

...

s.draw (); }

Circle c = new Circle (); Triangle t = new Triangle (); Line l = new Line ();

doStuff (c); // “ dynamic binding ” doStuff (t); doStuff (l);

Composition vs. Inheritance

Car Wheel [] Window[] Door [] Engine Pure composition: Code reuse Shape draw() erase () Circle draw() erase () Sqare draw() erase () Line draw() erase () Pure inheritance: interface duplication Useful
(22)

OOIS-11-98-StWe-Java 43

An

abstract

Instrument

• Abstract classes leave some part of the implementation open

• Some methods and data may only be defined

abstract class Instrument4 {

int i; // storage allocated for each public abstract void play ();

public String what () { return "Instrument4"; }

public abstract void adjust (); }

• Rest of the code is the same…

• Abstract classes cannot be instantiated by new

An Instrument

interface

• No “concrete” elements in interface • You don’t extend, you implement

interface Instrument {

void play (); // Automatically public String what();

void adjust (); }

class Guitar implements Instrument { public void play () {

System. out. println ("Guitar .play()"); }

public String what() { return " Guitar "; } public void adjust () {}

(23)

OOIS-11-98-StWe-Java 45

How to use Java on STS-Sun-Workstations?

• Set the paths PATH and CLASSPATH correctly by typing:

def_jdk12

• Create a file with your source code ending on .java • Compile your code:

javac filename.java

• Run your application java filename

References

Related documents

This study seeks to investigate and analyze Problems and prospects of garment exporting industries in Ethiopia particularly the case of Oromiya Region. For the sake

Important factors that could cause actual results to differ materially from those indicated by such forward-looking statements include, among others, risks related to: delays

Although Grand Kadis have statutory powers to make rules of court relating to the administration of estates in the Sharia Courts of Appeal, no Grand Kadi has

The company provides crane hire, heavy lift, project logistics management, oversize transport, materials handling, warehousing and storage with support bases located across

Природно, що в процесі аналізу стану виробничої структури фермерського підприємництва доцільно враховувати його специфічні особливості,

This study aimed to evaluate the effects of the treatment with haloperidol (HAL) associated with a high-fat diet (HF) on hepatic and renal damage, intracellular

Ravenswood Family Health Center Saint Louise Regional Hospital San Jose City College Health Center San Jose Foothill Family Community Clinic San Jose State University Health Center

To draw another line click the right mouse button and select Repeat LINE, or enter line on the command line.. New commands used in this section: spline, erase Video demo: