52
Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.M. Programmierpraktikum Programmierpraktium, C. Gros, SS2012 (19) 1 of 52 11/05/2012 09:18 AM

Institut für theoretische Physik Goethe-University

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Claudius Gros, SS2012

Institut für theoretische PhysikGoethe-University Frankfurt a.M.

Programmierpraktikum

Programmierpraktium, C. Gros, SS2012 (19)

1 of 52 11/05/2012 09:18 AM

Object-Oriented Programming (OOP)

Programmierpraktium, C. Gros, SS2012 (19)

2 of 52 11/05/2012 09:18 AM

principles

modularityThe source code for an object can be written and maintainedindependently and used by many distinct applications.

information hidingThe users needs to know only about the functionality of the publicmethods, the complexity of the internal details are hidden to the outsideworld (data abstraction).

inheritanceA class may inherite properties from other classes making it easy todefine subytpes (vehicle → car → cabriolet).

polymorphismA class may come with a range of distinct constructors and memberfunctions implementing semantically related task.

object-oriented programming

Programmierpraktium, C. Gros, SS2012 (19)

3 of 52 11/05/2012 09:18 AM

static double abs(double a);1.

static int abs(int a);2.

static long abs(long a);3.

object oriented programming tries to cast programming into structureresembling human though pathways

Programmierpraktium, C. Gros, SS2012 (19)

4 of 52 11/05/2012 09:18 AM

in Java objects are classes

classes can be defined in the same file as the executable classcontaining the main() function or in seperated files

classes may

extend another class

implement various interfaces

have user defined construtors

classes need to instantiated (with new) to create a modifiable instance

public class MyClass {1.

2.

int myVariable1; // member variables can be3.

double[] myVariable2; // private, public, static, ...4.

5.

/** Define any number of member functions (methods).6.

* They can have as return values any primitive data type or7.

classes and objects

Programmierpraktium, C. Gros, SS2012 (19)

5 of 52 11/05/2012 09:18 AM

* any predefined or user defined object, or nothing (void).8.

*/9.

void myFunction1 () {10.

} // end of MyClass.myFunction1()11.

12.

} // end of class MyClass13.

Programmierpraktium, C. Gros, SS2012 (19)

6 of 52 11/05/2012 09:18 AM

private variables (functions) can be accessed only within the definingclassit is custom to use standardized public functions to modify privatevariables (getter/setter)

public variables (functions) can be accessed by other classes

contains no main() method not executable by itself

public class BookBasic {1.

2.

private int itemCode; // Internal variables.3.

private String title;4.

5.

/* Standard getter for itemCode.6.

*/7.

public int getItemCode() {8.

return itemCode;9.

}10.

object definition example: BookBasics

Programmierpraktium, C. Gros, SS2012 (19)

7 of 52 11/05/2012 09:18 AM

11.

/* Standard setter for itemCode, returns 'true' if12.

* itemCode is valid, otherwise 'false'.13.

*/14.

public boolean setItemCode (int newItemCode) {15.

if (newItemCode > 0) { // a given constraint16.

itemCode = newItemCode;17.

return true;18.

} else19.

return false;20.

}21.

22.

/* Standard getter for title.23.

*/24.

public String getTitle() {25.

return title;26.

}27.

28.

/* Standard setter for title.29.

*/30.

public void setTitle (String newTitle) {31.

title = newTitle;32.

}33.

Programmierpraktium, C. Gros, SS2012 (19)

8 of 52 11/05/2012 09:18 AM

34.

/* Non-trivial member function.35.

*/36.

public void display() {37.

System.out.println(itemCode + " " + title);38.

}39.

} // end of class BookBasic 40.

Programmierpraktium, C. Gros, SS2012 (19)

9 of 52 11/05/2012 09:18 AM

access member functions inside residing class:functionName(args) orthis.functionName(args) if function overloads an inherited function

access member functions from the outside:name.functionName(args) wherename is the name of the instantiated class object

public class UseBookBasic {1.

2.

public static void main(String[] args) {3.

BookBasic b = new BookBasic(); // instantiation of a book4.

b.setItemCode(5011); // code of book5.

b.setTitle("Fishing Explained"); // book title6.

7.

// --- printing by hand and using the printing routine of BookBasic8.

System.out.println(b.getItemCode() + " " + b.getTitle());9.

System.out.print("From BookBasic.display(): ");10.

b.display();11.

object definition usuage: BookBasics

Programmierpraktium, C. Gros, SS2012 (19)

10 of 52 11/05/2012 09:18 AM

}12.

} 13.

14.

// *** *************** *** 15.

// *** class BookBasic *** 16.

// *** *************** *** 17.

18.

class BookBasic {19.

20.

private int itemCode;21.

private String title;22.

23.

public int getItemCode() { return itemCode; }24.

25.

public boolean setItemCode (int newItemCode) {26.

if (newItemCode > 0) {27.

itemCode = newItemCode;28.

return true;29.

} else30.

return false;31.

}32.

33.

public String getTitle() { return title; }34.

Programmierpraktium, C. Gros, SS2012 (19)

11 of 52 11/05/2012 09:18 AM

35.

public void setTitle (String newTitle) {36.

title = newTitle;37.

}38.

39.

public void display() {40.

System.out.println(itemCode + " " + title);41.

}42.

}43.

Programmierpraktium, C. Gros, SS2012 (19)

12 of 52 11/05/2012 09:18 AM

publicA public class or member function can be accessed by other classes.Filename must match class name.

privateA private variable or member function can be accessed only inside theresiding class.

abstractAn abstract class may not be instantiated, only respective subclasse may(similar to interfaces).

finalFinal classes / methods / variablescannot be extended / overwritten / changed.

staticA static class always exists, even if not instantiated, and can be accessed

Java access modifiers

Programmierpraktium, C. Gros, SS2012 (19)

13 of 52 11/05/2012 09:18 AM

directly.

double x = Math.random(); // the class Math is static and 1.

double y = Math.sqrt(x); // needs not to be instantiated2.

Programmierpraktium, C. Gros, SS2012 (19)

14 of 52 11/05/2012 09:18 AM

the constructor specifies what to do when instantiating a class,it has per definition the name of the residing class

the constructor function has no return value

public class BookWithConstructor {1.

2.

private int itemCode;3.

private String title;4.

5.

/* User defined constructor.6.

*/7.

public BookWithConstructor(int newItemCode, String newTitle) {8.

setItemCode(newItemCode); // use always the setter if existing,9.

setTitle(newTitle); // there might be contraints 10.

}11.

12.

public int getItemCode() {13.

return itemCode;14.

class constructors

Programmierpraktium, C. Gros, SS2012 (19)

15 of 52 11/05/2012 09:18 AM

}15.

public boolean setItemCode (int newItemCode) {16.

if (newItemCode > 0) {17.

itemCode = newItemCode;18.

return true;19.

} else20.

return false;21.

}22.

public String getTitle() {23.

return title;24.

}25.

public void setTitle (String newTitle) {26.

title = newTitle;27.

}28.

public void display() {29.

System.out.println(itemCode + " " + title);30.

}31.

}32.

Programmierpraktium, C. Gros, SS2012 (19)

16 of 52 11/05/2012 09:18 AM

with new a new instantiation (realization) of a class is created

new ... () calls the class constructor

there is no limit on the number of instantiations

public class UseBookWithConstructor {1.

2.

public static void main(String[] args) {3.

BookWithConstructor b =4.

new BookWithConstructor(5011, "Fishing Explained");5.

b.display();6.

}7.

}8.

9.

// ********************************* 10.

// *** class BookWithConstructor ***11.

// ********************************* 12.

13.

class BookWithConstructor {14.

class instantiation

Programmierpraktium, C. Gros, SS2012 (19)

17 of 52 11/05/2012 09:18 AM

15.

private int itemCode;16.

private String title;17.

18.

/* User defined constructor.19.

*/20.

public BookWithConstructor(int newItemCode, String newTitle) {21.

setItemCode(newItemCode);22.

setTitle(newTitle);23.

}24.

25.

public int getItemCode() {26.

return itemCode;27.

}28.

public boolean setItemCode (int newItemCode) {29.

if (newItemCode > 0) {30.

itemCode = newItemCode;31.

return true;32.

} else33.

return false;34.

}35.

public String getTitle() {36.

return title;37.

Programmierpraktium, C. Gros, SS2012 (19)

18 of 52 11/05/2012 09:18 AM

}38.

public void setTitle (String newTitle) {39.

title = newTitle;40.

}41.

public void display() {42.

System.out.println(itemCode + " " + title);43.

}44.

}45.

Programmierpraktium, C. Gros, SS2012 (19)

19 of 52 11/05/2012 09:18 AM

methods may be overloaded when differing byargument type (or number) and/or return value

public class BookMultiConstructor {1.

private int itemCode;2.

private String title;3.

4.

/* The first constructor.5.

*/6.

public BookMultiConstructor(int newItemCode, String newTitle) {7.

setItemCode(newItemCode);8.

setTitle(newTitle);9.

}10.

11.

/* The second constructor.12.

*/13.

public BookMultiConstructor(String newTitle) {14.

setItemCode(0);15.

setTitle(newTitle);16.

method overloading (polymorphism)

Programmierpraktium, C. Gros, SS2012 (19)

20 of 52 11/05/2012 09:18 AM

}17.

18.

public int getItemCode() {19.

return itemCode;20.

}21.

public boolean setItemCode (int newItemCode) {22.

if (newItemCode > 0) {23.

itemCode = newItemCode;24.

return true;25.

} else26.

return false;27.

}28.

public String getTitle() {29.

return title;30.

}31.

public void setTitle (String newTitle) {32.

title = newTitle;33.

}34.

public void display() {35.

System.out.println(itemCode + " " + title);36.

}37.

}38.

Programmierpraktium, C. Gros, SS2012 (19)

21 of 52 11/05/2012 09:18 AM

keep class BookMultiConstructor as seperated class file

you need to compile only the class containing the .main() methodall other classed needed are automatically included from current path

public class UseBookMultiConstructor {1.

public static void main(String[] args) {2.

3.

BookMultiConstructor b =4.

new BookMultiConstructor(5011, "Fishing Explained");5.

b.display();6.

// note the immediate call to a method on a new instance7.

new BookMultiConstructor("Dogs I've Known").display();8.

}9.

}10.

Programmierpraktium, C. Gros, SS2012 (19)

22 of 52 11/05/2012 09:18 AM

abstract classes with static functionsare convenient for general purpose utilities

any class can contain static functions

return types of member function can be a primitive data types,an objects (class) or void:boolean, int[], void, ...

public class MyUtilityDemo {1.

2.

public static void main(String[] args)3.

{4.

double rr = 11.123456;5.

MyUtility.printString("initial rr: " + String.valueOf(rr));6.

rr = MyUtility.roundToDigits(rr, 2);7.

MyUtility.printString(" 2 digits: " + String.valueOf(rr));8.

} // end of MyUtilityDemo.main()9.

10.

static functions

Programmierpraktium, C. Gros, SS2012 (19)

23 of 52 11/05/2012 09:18 AM

} // end of class MyUtilityDemo11.

12.

// *** *************** ***13.

// *** class MyUtility ***14.

// *** *************** ***15.

16.

/** Example of a abstract (cannot be instantiated) class.17.

* An abstract class can have only static member functions.18.

*/19.

abstract class MyUtility {20.

21.

/** Just printing a String to standard ouput.22.

* Can be generalized to print (append) data to a file.23.

*/24.

static void printString(String output)25.

{26.

System.out.println("MyUtility.printString():: " + output);27.

}28.

29.

/** Rounds to n digits accuracy.30.

*/31.

static double roundToDigits(double input, int nDigits)32.

{33.

Programmierpraktium, C. Gros, SS2012 (19)

24 of 52 11/05/2012 09:18 AM

for (int i=0; i<nDigits; i++)34.

input *= 10.0;35.

input = Math.round(input);36.

for (int i=0; i<nDigits; i++)37.

input *= 0.1;38.

return input;39.

}40.

41.

} // end of class MyUtility42.

Programmierpraktium, C. Gros, SS2012 (19)

25 of 52 11/05/2012 09:18 AM

hierarchical object definition possible

a class which extends another class inherits all its member functionsand variables

an interface is implemented and not extended

a class can extend only one other class but can implement manyinterfaces

the parent (root) of all classes is the Object class

public class ExtendingDemo {1.

2.

public static void main(String[] args) {3.

4.

System.out.println(" ");5.

6.

ExtendingSimpleClass esc = new ExtendingSimpleClass(3);7.

System.out.printf("calling ExtendingSimpleClass.getTopSecret() : %d\n",8.

extending and inheriting

Programmierpraktium, C. Gros, SS2012 (19)

26 of 52 11/05/2012 09:18 AM

esc.getTopSecret()); // inherited from SimpleClass9.

System.out.printf("calling ExtendingSimpleClass.secretPrinting(): ");10.

esc.secretPrinting();11.

12.

// --- an ExtendingSimpleClass is a SimpleClass13.

SimpleClass sc = new ExtendingSimpleClass(4);14.

int dummy = sc.getTopSecret(); // possible15.

// sc.secretPrinting(); // error16.

((ExtendingSimpleClass)sc).secretPrinting(); // possible: casting beforehand to subclass17.

18.

// --- all classes are objects19.

Object o1 = new ExtendingSimpleClass(5);20.

Object[] o2 = new String[7];21.

22.

} // end of ExtendingDemo.main()23.

} // end of class ExtendingDemo24.

25.

// *** ************************** ***26.

// *** class ExtendingSimpleClass ***27.

// *** ************************** ***28.

29.

class ExtendingSimpleClass extends SimpleClass {30.

31.

Programmierpraktium, C. Gros, SS2012 (19)

27 of 52 11/05/2012 09:18 AM

public ExtendingSimpleClass(int topSecret)32.

{33.

super(topSecret); // calls the constructor of the parent class34.

}35.

public void secretPrinting()36.

{37.

System.out.printf("printing from ExtendingSimpleClass: %d\n\n",getTopSecret());38.

}39.

} // end of class ExtendingSimpleClass40.

41.

// *** ***************** ***42.

// *** class SimpleClass ***43.

// *** ***************** ***44.

45.

class SimpleClass {46.

private int topSecret; // a private variable47.

public SimpleClass(int topSecret){ this.topSecret = topSecret; } // a constructor48.

public int getTopSecret(){ return topSecret; } // a standard getter49.

} // end of class SimpleClass50.

51.

Programmierpraktium, C. Gros, SS2012 (19)

28 of 52 11/05/2012 09:18 AM

main() can run without instatiation being static and public

the main() method can also be called explicitly, as any other staticfunction

public class MainDemo {1.

2.

/** A static variable counting the number of times main() was called.3.

*/4.

public static int counter = 0;5.

6.

/** A non-static variable, can only be accessed when 7.

* MainDemo has been instatiated.8.

*/9.

public String myName;10.

11.

/** Constructor for MainDemo,12.

* this.myName refers to the member variable of the13.

* current (this) instantion.14.

the main method

Programmierpraktium, C. Gros, SS2012 (19)

29 of 52 11/05/2012 09:18 AM

*/15.

public MainDemo()16.

{17.

this.myName = "I am class number " + MainDemo.counter;18.

}19.

20.

/** The main() function is called when starting.21.

* Per definitions it has an String array as argument.22.

*/23.

public static void main(String[] args)24.

{25.

26.

// note the two ways to access: 27.

// MainDemo.counter : always possible28.

// counter : only from inside MainDemo29.

MainDemo.counter++;30.

System.out.printf("number of times main() was called: %d\n",counter);31.

32.

// MainDemo itself can be instatiated33.

MainDemo newMainDemo = new MainDemo();34.

System.out.printf(" name of newMainDemo: %s\n",35.

newMainDemo.myName);36.

37.

Programmierpraktium, C. Gros, SS2012 (19)

30 of 52 11/05/2012 09:18 AM

// the main method is static and can be called38.

// with a string array as an argument,39.

// the if-condition avoids an infinite recursion loop40.

if (MainDemo.counter < 7)41.

MainDemo.main(new String[2]);42.

43.

} // end of MainDemo.main()44.

} // end of class MainDemo45.

Programmierpraktium, C. Gros, SS2012 (19)

31 of 52 11/05/2012 09:18 AM

Any user defined object, of arbitray complexity,can by used by any other object, eg by arrays

public class ObjectOfObjects {1.

2.

/** Escape sequences for colored console output,3.

* may be operating system dependent.4.

* Just for the fun of it.5.

*/6.

public static final String ANSI_BLACK = "\u001B[30m";7.

public static final String ANSI_RED = "\u001B[31m";8.

public static final String ANSI_GREEN = "\u001B[32m";9.

public static final String ANSI_YELLOW = "\u001B[33m";10.

public static final String ANSI_BLUE = "\u001B[34m";11.

public static final String ANSI_MAGENTA = "\u001B[35m";12.

public static final String ANSI_CYAN = "\u001B[36m";13.

public static final String ANSI_WHITE = "\u001B[37m";14.

public static final String ANSI_RESET = "\u001B[m";15.

16.

objects of objects

Programmierpraktium, C. Gros, SS2012 (19)

32 of 52 11/05/2012 09:18 AM

public static void main(String[] args)17.

{18.

19.

// --- create array of ColoredObject20.

ColoredObject[] manyObjects = new ColoredObject[3];21.

22.

// --- instantiate the individual array elements23.

manyObjects[0] = new ColoredObject("I am red (hopefully) ",24.

ObjectOfObjects.ANSI_RED);25.

manyObjects[1] = new ColoredObject("sure, but I am green ",26.

ObjectOfObjects.ANSI_GREEN);27.

manyObjects[2] = new ColoredObject("yes, but blue is best",28.

ObjectOfObjects.ANSI_BLUE);29.

30.

// --- print colored objects line by line31.

// --- ANSI_RESET resets the output color32.

System.out.println(" ");33.

for (int i=0; i<manyObjects.length; i++)34.

{35.

String outString = manyObjects[i].getColor()36.

+ manyObjects[i].getText()37.

+ ObjectOfObjects.ANSI_RESET;38.

System.out.println(outString);39.

Programmierpraktium, C. Gros, SS2012 (19)

33 of 52 11/05/2012 09:18 AM

}40.

41.

System.out.println(" ");42.

System.out.println("and I am boring black (again)");43.

System.out.println(" ");44.

45.

} // end of ObjectOfObjects.main()46.

} // end of class ObjectOfObjects47.

48.

// *** ******************* ***49.

// *** class ColoredObject ***50.

// *** ******************* ***51.

52.

class ColoredObject {53.

54.

private String myAnsiColor;55.

private String myText;56.

57.

public ColoredObject(String text, String color)58.

{59.

this.myText = text;60.

this.myAnsiColor = color;61.

}62.

Programmierpraktium, C. Gros, SS2012 (19)

34 of 52 11/05/2012 09:18 AM

63.

public String getColor(){return this.myAnsiColor;}64.

public String getText(){return this.myText;}65.

66.

} // end of class ColoredObjects67.

Programmierpraktium, C. Gros, SS2012 (19)

35 of 52 11/05/2012 09:18 AM

everything, besides primitive data typesint, double, boolean, ... , is an object

the name of an object is a reference to it,the place in memory where the object starts,and not the object itself

String objects are special:every single String operation creates a new String object

public class ReferenceDemo {1.

2.

public static void main(String[] args)3.

{4.

5.

// aInt and bInt are two distinct integer variables6.

int aInt = 1;7.

int bInt = aInt;8.

System.out.printf("aInt, bInt: %d | %d\n",aInt,bInt);9.

reference to objects

Programmierpraktium, C. Gros, SS2012 (19)

36 of 52 11/05/2012 09:18 AM

bInt = 2;10.

System.out.printf("aInt, bInt: %d | %d\n",aInt,bInt);11.

System.out.println(" ");12.

13.

// bArray is a synonym for aArray 14.

// bArray is not a new object15.

int[] aArray = { 1, 2, 3};16.

int[] bArray = aArray;17.

System.out.printf("aArray: %d %d %d\n",aArray[0],aArray[1],aArray[2]);18.

System.out.printf("bArray: %d %d %d\n",bArray[0],bArray[1],bArray[2]);19.

System.out.println(" ");20.

21.

aArray[0] = 0;22.

System.out.printf("aArray: %d %d %d\n",aArray[0],aArray[1],aArray[2]);23.

System.out.printf("bArray: %d %d %d\n",bArray[0],bArray[1],bArray[2]);24.

System.out.println(" ");25.

26.

bArray[2] = 7;27.

System.out.printf("aArray: %d %d %d\n",aArray[0],aArray[1],aArray[2]);28.

System.out.printf("bArray: %d %d %d\n",bArray[0],bArray[1],bArray[2]);29.

System.out.println(" ");30.

31.

// String operations always create new String objects32.

Programmierpraktium, C. Gros, SS2012 (19)

37 of 52 11/05/2012 09:18 AM

String aStr = "a comes first";33.

String bStr = aStr; // a new String object is created implicitly34.

System.out.printf("aStr, bStr: %s | %s\n",aStr,bStr);35.

36.

// creating a new String object 'b comes second' and37.

// assigning its reference to the variable bStr 38.

bStr = "b comes second";39.

System.out.printf("aStr, bStr: %s | %s\n",aStr,bStr);40.

System.out.println(" ");41.

42.

} // end of ReferenceDemo.main()43.

} // end of class ReferenceDemo44.

Programmierpraktium, C. Gros, SS2012 (19)

38 of 52 11/05/2012 09:18 AM

call by valueWhen a function f(arg) is called only the value of the argument arg ispassed, not its references.Changes of the argument inside the function f() do not change the valueof the argument outside of the function.

call by referenceWhen a function f(arg) is called only the reference of arg is passed to thefunction.Changes of the argument inside the function f() do change the value ofthe argument outside of the function.

JAVA

primitive data types -- call by value

objects -- call by reference

public class FunctionCallDemo {1.

2.

call by value / call by reference

Programmierpraktium, C. Gros, SS2012 (19)

39 of 52 11/05/2012 09:18 AM

/** Changing the value of a primitive data type has3.

* has no effect outside the residing function,4.

* call-by-value only passes the value and not the5.

* reference of a primitive data type.6.

*/7.

public static void callByValue(int inputInteger)8.

{9.

System.out.printf("in FunctionCallDemo.callByValue(), "10.

+ "inputInteger : %d\n",inputInteger);11.

inputInteger = 0;12.

}13.

14.

/** Only the reference, not the value, of Objects are15.

* passed to the function, creating a synonym of the argument.16.

*/17.

public static void callByReference(int[] inputArray)18.

{19.

inputArray[0] = 0;20.

}21.

22.

public static void main(String[] args)23.

{24.

25.

Programmierpraktium, C. Gros, SS2012 (19)

40 of 52 11/05/2012 09:18 AM

// --- call by value, for primitive data types26.

int callInteger = 10;27.

System.out.println(" ");28.

FunctionCallDemo.callByValue(callInteger);29.

System.out.printf(" in FunctionCallDemo.main(), "30.

+ " callInteger : %d\n",callInteger);31.

System.out.println(" ");32.

33.

// --- call by value, for objects34.

int[] callArray = { 33, 44, 55};35.

System.out.printf(" in FunctionCallDemo.main(), "36.

+ " callArray : %2d %2d %2d\n",37.

callArray[0], callArray[1], callArray[2]);38.

FunctionCallDemo.callByReference(callArray);39.

System.out.printf(" in FunctionCallDemo.main(), "40.

+ " callArray : %2d %2d %2d\n",41.

callArray[0], callArray[1], callArray[2]);42.

43.

} // end of FunctionCallDemo.main()44.

} // end of class FunctionCallDemo45.

Programmierpraktium, C. Gros, SS2012 (19)

41 of 52 11/05/2012 09:18 AM

one file per class

standard: file MyClass only contains the class MyClass

idea: classes can be used by many programs, interchangeability

needed: one directory per project

one program per file

best for small/medium projects:file MyProgram contains the class MyProgram and all (self written)referenced classes

advantage: reuse (after an extended period of inactivity)and transfer (eg via email) straightforward

public class MyProgram {1.

2.

public static void main(String[] args)3.

classes and files

Programmierpraktium, C. Gros, SS2012 (19)

42 of 52 11/05/2012 09:18 AM

{4.

MyClass mc = new MyClass();5.

// ...6.

} 7.

} 8.

9.

// *** ************* ***10.

// *** class MyClass ***11.

// *** ************* ***12.

13.

class MyClass {14.

// ...15.

} 16.

Programmierpraktium, C. Gros, SS2012 (19)

43 of 52 11/05/2012 09:18 AM

API - application programming interfacea common interface (standard) for possibly many applications and/orrealizations

defines abstract methods without implementing them

a class implenting an interface must (mandatory)overwrite all methods of an interface

a class can can implement many interfaces

interface MovingHero {1.

2.

public String getSymbol(); // symbol of hero3.

public int getPosition(); // position of hero4.

public void move(); // move the hero5.

public void invertDirection(); // invert direction of movement6.

7.

}8.

interfaces

Programmierpraktium, C. Gros, SS2012 (19)

44 of 52 11/05/2012 09:18 AM

Programmierpraktium, C. Gros, SS2012 (19)

45 of 52 11/05/2012 09:18 AM

Unicode symbols like \u0040 can be printed

the control sequence \r moves the pointer (for writing to the output)to the start of the line

exercise: add a green hero

public class InterfaceDemo {1.

2.

/** The length of the battlefield.3.

*/4.

public static final int length = 30;5.

6.

public static void main(String[] args)7.

throws Exception8.

{9.

10.

// -- create array of hero (interfaces, not classes11.

MovingHero[] allHeros = new MovingHero[2];12.

interface demo - inline battle

Programmierpraktium, C. Gros, SS2012 (19)

46 of 52 11/05/2012 09:18 AM

13.

// -- instantiate the heros, with classe now14.

allHeros[0] = new BlueHero(InterfaceDemo.length);15.

allHeros[1] = new RedHero(InterfaceDemo.length);16.

17.

// -- the configuration of the heros on the battlefield18.

String[] heroPos = new String[InterfaceDemo.length];19.

20.

System.out.println(" ");21.

22.

// -- let the heros battle each other23.

for (int i=0; i<100; i++)24.

{25.

for (int h=0; h<heroPos.length; h++) // empty battlefield26.

heroPos[h] = " ";27.

for (int a=0; a<allHeros.length; a++) // loop over all heros28.

{29.

int pos = allHeros[a].getPosition();30.

if (heroPos[pos].equals(" "))31.

heroPos[pos] = allHeros[a].getSymbol(); // draw hero32.

else33.

allHeros[a].invertDirection(); // invert if colliding34.

allHeros[a]. move(); // move them35.

Programmierpraktium, C. Gros, SS2012 (19)

47 of 52 11/05/2012 09:18 AM

}36.

37.

for (int l=0; l<heroPos.length; l++) // print battlefield38.

System.out.printf("%s",heroPos[l]);39.

40.

// --- no linebreak, return to beginning of line41.

System.out.print("\r");42.

43.

// --- pause the program execution (ms)44.

Thread.sleep(200);45.

//46.

} // end of loop over all steps47.

48.

49.

} // end of InterfaceDemo.main()50.

} // the dof class InterfaceDemo51.

52.

// *** ********************** ***53.

// *** Interface moving heros ***54.

// *** ********************** ***55.

56.

/** Any here hero is a moving hero.57.

*/58.

Programmierpraktium, C. Gros, SS2012 (19)

48 of 52 11/05/2012 09:18 AM

interface MovingHero {59.

60.

public String getSymbol(); // symbol of hero61.

public int getPosition(); // position of hero62.

public void move(); // move the hero63.

public void invertDirection(); // invert direction of movement64.

65.

} // end of interface MovingHero66.

67.

// *** ************** ***68.

// *** class red hero ***69.

// *** ************** ***70.

71.

class RedHero implements MovingHero {72.

73.

private static final String mySymbol = "\u001B[31m" + "\u0040" + "\u001B[m";74.

private int myPos;75.

private int mySpeed = 2;76.

private int length;77.

78.

public RedHero (int length)79.

{80.

this.myPos = (int)(Math.random()*length);81.

Programmierpraktium, C. Gros, SS2012 (19)

49 of 52 11/05/2012 09:18 AM

this.length = length;82.

}83.

84.

public String getSymbol() 85.

{86.

return this.mySymbol;87.

}88.

public int getPosition()89.

{90.

return this.myPos;91.

}92.

public void move()93.

{94.

this.myPos = (this.myPos+this.mySpeed+this.length)%this.length;95.

}96.

public void invertDirection()97.

{98.

this.mySpeed *= -1;99.

}100.

101.

} // end of class RedHero102.

103.

// *** *************** ***104.

Programmierpraktium, C. Gros, SS2012 (19)

50 of 52 11/05/2012 09:18 AM

// *** class blue hero ***105.

// *** *************** ***106.

107.

class BlueHero implements MovingHero {108.

109.

private static final String mySymbol = "\u001B[34m" + "\u0026" + "\u001B[m";110.

private int myPos;111.

private int length;112.

113.

public BlueHero (int length)114.

{115.

this.myPos = (int)(Math.random()*length);116.

this.length = length;117.

}118.

119.

public String getSymbol() 120.

{121.

return this.mySymbol;122.

}123.

public int getPosition()124.

{125.

return this.myPos;126.

}127.

Programmierpraktium, C. Gros, SS2012 (19)

51 of 52 11/05/2012 09:18 AM

public void move()128.

{129.

this.myPos = (this.myPos + 1)%this.length;130.

}131.

public void invertDirection()132.

{133.

}134.

135.

} // end of class BlueHero136.

Programmierpraktium, C. Gros, SS2012 (19)

52 of 52 11/05/2012 09:18 AM