Unterschiede zwischen C# und Java

Werbung
Heilbronn, 23.05.05
Unterschiede zwischen
C# und Java.doc
Seite 1 von 8
Differences between C# and Java in terms, keywords and syntax
Stand: 23. Mai 2005
Literature:
• Deitel et al.: C# how to program, Prentice Hall, 2002.
• Hanisch, A.: GoTo C# (in German). Addison-Wesley, 2002. (€ 40)
• Mössenböck, H.: Softwareentwicklung mit C# (in German). dpunkt.verlag, 2003 (€ 29)
Ch.
Ch.
Java
Java sources (.java)
1
Ch.
2
compile
C#
C# sources (.cs) (or other language)
"javac"
compile
"csc"
Java Bytecode (.class)
MS Intermediate Language (MSIL)
+ Java foundation class library (JFC)
+ Framework class library (FCL)
[ optionally: compress to .jar ]
link into => executable file (.exe)
Java Virtual Machine
Common Language Runtime (CLR)
processor
processor
Visual Studio .NET Overview, ch. 2.2, p. 34
-
(classpath with several entries)
-
"solution" = group of projects ("Projektmappe")
-
project pane in JBuilder, on left
-
"Solution explorer"= tree view of solutions,
projects, and files on right side
-
component palette in JBuilder
ASimpleProject ch. 2.6 p. 44, Form1.cs
-
JLabel, define an ImageIcon in
-
"Toolbox" = palettes of controls for GUI
constructor
-
Images go in "picture box control": PNG, GIF,
-
Ch.
3
JPEG, BMP or ICO formats
JBuilder:
[Design] tab: construct forms visually
-
[design] mode: construct forms visually
[Source] tab: view Java source
-
[run] mode: build, then execute Program
Case Sensitive!
Case Sensitive! Ch 3.2, Welcome1, Fig. 3.1,p. 60
convention: class names in upper case,
class names and methods start with upper case,
fields and methods in lower case
fields in lower case | Create Console App, p. 65
namespace (as in ANSI/ISO C++)
package
package xyz; // at beginning of file
import : import classes fr. other package
System.out
: output channel to console
namespace xyz { ... }
using
(as for namespaces in C++)
System.Console
print, println
Write, WriteLine
static void main(String[] args)
static void Main(string[] args)
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Heilbronn, 23.05.2005
Unterschiede zwischen C# und Java.doc
Seite 2
static main()in any
class file
just one Main() allowed in any project
comments for javadoc:
documentation comments:
/** Description...
/// <summary>
*/
/// Description...
/// </summary>
MSDN Doc (Help | Index in MS Visual Studio .NET)
JDK API documentation
set classpath env. var. to include libraries
1. add reference to library to project;
use import statement
2. use using statement
reading input string from console:
reading input string from console:
new BufferedReader
prog. Addition, ch. 3.3, fig. 3.11, p. 72
(new InputStreamReader(System.in))
System.Console.ReadLine()
.readLine()
Ch.
4,
5
converting to number:
converting to number:
Integer.parseInt(String s)
Int32.Parse(String s)
C# keywords on Deitel p. 98 f.
Control structures as in C, C++
Control structures as in C, C++, Java
post-/prefix operators a--, ++i
as in C++, Java
JBuilder X code editor does that, too
MS Visual Editor structures code in segments,
can open and collapse them (as in tree view)
Ch.
6
Math
class static methods,
Math
class static methods: see list
Java1.5: import static java.lang.Math.*;
double click on GUI control à ch.6.5, fig. 6.3
add listener with actionPerformed(…) to
empty handler method is created and added
component (JBuilder)
e.g. calculateButton_Click
JDK API classes and interfaces
6.7 Predefined namespaces, classes
primitive data types
6.8 'value type' data, including 16 bit and 8 bit list
call by value for primitive variables,
6.9 explicit call by reference
call by reference for objects only
cbref.: for 'ref', 'out' parameters of value type
see list
('out' need not be initialized before) fig. 6.8, p.198
Ch.
7
Enumeration types, constants (Java 1.5):
Enumeration types, constants: ch. 6.11, fig. 6.12
enum Color { BLUE,
// = 0
RED,
// = 1
GREEN = 3}
if (c == Color.RED) …
enum Color { BLUE,
// = 0
RED,
// = 1
GREEN = 3}
if (c == Color.RED) …
Method overloading (different signatures)
as in Java
float[] myArray = new float[12];
as in Java
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Heilbronn, 23.05.2005
Unterschiede zwischen C# und Java.doc
Seite 3
myArray[6] = 66.6; // write
ch. 7.4, fig. 7.3, p. 240f.
float f = myArray[2]; // read
int[] x = {32, 27, 90}; // initialize
as in Java
// two-dim. array:
// two-dim. array:
float[][] matrix = new float[3][12];
float[,] matrix =
for (float nbr : myArray) {...}//J1.5
foreach (float nbr in myArray) {...}fig7.16
myArray.length; // no. poss. elements
// ch. 7.10, fig 7.13
new float[3, 12];
myArray.Length; // no. of possible elements
Arrays are passed by reference (as pointers)
Ch.
8
from C, C++, [Java]:
ch8.7,f.8.6:(expression) ? trueVal:falseVal
printf("the %s is %d2", str, nr)
String.Format("the {0} is {1:D2}", str, nr)
this
in method: handle to present object
public/protected/private/[in package]
as in Java
public/protected/private/
internal = in same assembly (see ch. 9.3)
class XYZ { // initialize field
as in Java (unlike C++)
int firstAtt = 45; }
bean properties: setter and getter methods ch. 8.7; properties: set and get accessor
class OurBean {
private int myProp;
public void setMyProp(int val) {
myProp = val; }
int getMyProp() { return myProp; }
}
class OurClass {
ch8.7,fig. 8.6, p.298f.
private int myProp;
public int MyProp {
set { myProp = value; } // 'value' is
get { return myProp; } // a keyword!
}
OurBean myBean = new OurBean();
myBean.setMyProp(6);
int x = myBean.getMyProp();
OurClass myObj = new OurClass();
myObj.MyProp = 6;
// property set
int x = myObj.MyProp; // property get
Garbage collection (automatic)
ch 8.10: as in Java
myObj.finalize() // finalize() method
~OurClass()
is called on removal of object
as in Java
static memb. variables: one val per class
final member variables: value invariable
ch. 8.11: as in Java
ch. 8.12: const member variables: are static,
initialize in declaration statement
readonly member variables: initialize in
declaration statement or in any constructor
ch. 8.12, fig. 8.15, p. 318f.
ch 8.13: "Indexer property" fig. 8.16, p. 320 ff.
import java.util.HashMap; //Java1.5
class Whole {
private HashMap<String, Part> parts
= new HashMap<String, Part>();
public void addPart(String partId,
Part newPart) {
parts.put(partId, newPart); }
public Part getPart(String partId) {
// Destructor = Finalizer
class Whole {
private Part[] parts = new Part[MAX_PARTS];
private string[] allIds = {"id1", "id2" };
public Part this[string partId] {
get {
int i = 0;
while(i < allIds.Length
&& partId != allIds[i])
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Heilbronn, 23.05.2005
Unterschiede zwischen C# und Java.doc
Seite 4
return parts.get(partId); }
}
UML: qualified association
Whole
partId
Part
}
set {
int i = 0;
while(i< allIds.Length
&& partId != allIds[i])
i++; // linear search
if (i != allIds.Length) // found!
parts[i] = value; // keyword
}
------------------------------------Whole myWhole = new Whole();
Part aPart = new Part();
myWhole.addPart("id2", aPart);
Part thePart =myWhole.getPart("id2");
}
------------------------------------Whole myWhole = new Whole();
Part aPart = new Part();
myWhole["id2"] = aPart; //"id2" must exist!
Part thePart = myWhole["id2"];
Packages
ch 8.16: Namespaces
package de.fhheilbronn.se.timelib;
public class Time3 {
...
}
one (public) class per file
Building .jar archives from .class files:
jar cf lib.jar Foo.class Bar.class
class browser in JBuilder, Eclipse
JDK API documentation
Ch.
9
i++; // linear search
if (i == allIds.Length) return null;
else return parts[i];
namespace TimeLib {
// in UML: package
public class Time3 {
...
}
// more classes in namespace
} // end of namespace
New Project | Class Library // UML: component
creates a DLL, one type of "assembly".
Only public classes are accessible from outside.
ch 8.17:
Visual Studio Class View: tree view with nodes
for project, class, "instance variables", methods,
Bases and Interfaces.
Object browser (right click on any built-in class)
list all classes from FCL with prop's & methods
Every class inherits from 'Object'
non-defaultInheritance:
Every class inherits from 'Object'
ch 9.4, fig. 9.10: Inheritance: ':' (colon) as in C++
class SubClass extends SuperClass
class ChildClass: BaseClass
Point3
Prohibit overriding of method:
fig. 9.10: Allow overriding of method:
public final String myMethod();
public virtual double Area();
x : int
y : int
calling superclass method:
fig. 9.13: calling base class method:
super.toString();
base.ToString();
Circle4
Override:
fig. 9.13: Override base class method:
public String toString();
public override string ToString();
radius :
float
y : int
Default constructor is called implicitly
As in Java
ch. 9.6, fig. 9.18:
Use non-default constructor of superclass: Use non-default constructor of base class
public ChildClass(int x, float f) {
super(x, f); // must be first stmt
... // more constructor code
public ChildClass (int x, int y, float f)
: base (x, f) {
... // more constructor code
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Heilbronn, 23.05.2005
Unterschiede zwischen C# und Java.doc
Seite 5
Constructor of subclass may call
Constructor of derived class calls constructor of
constructor of superclass in first statement base class first fig. 9.17..9.19
Finalizer calling finalizer of superclass:
super.finalize()
??
Destructor of derived class calls destructor of
base class last
Explicit start of garbage collection:
System.GC.Collect();
Ch.
10
Polymorphism:
ch. 10.2, fig. 10.1 .. 10.3
Shape
subclass object can fill superclass handle
class Circle: Point { … };
Area = 0
Vol = 0
anytime (implicit upcast)
Point p = new Circle ();
superclass object can fill subclass handle
only if it is an instance of the subclass
Point
(explicit downcast) :
Area
Vol
if (p instanceof Circle)
…println((Circle)p).toString();
if (p is Circle)
WriteLine((Circle)p).ToString();
Abstract class: cannot be instantiated
ch. 10.5..6, fig. 10.4: abstract class Shape
Abstract method: has no body,
as in Java. Abstract property: no body. fig.10.4..8
allowed only in abstract class or interface
as in Java. (virtual method/property: see ch. 9 !)
final
class: not to be used as superclass
ch. 10.7: sealed class: do not use as base class
final
method: not to be overridden
sealed
method: not to be overridden
static
and private methods implicitly sealed
"Interface" = like an abstract class with
[ch. 10.9]: "Interface" = like an abstract class with
abstract methods and final attributes only
abstract methods and abstract properties only
interface Employee {
// method signatures; final atts.
int calculateSalary();
final int maxSalary = 1000000;
}
public interface IEmployee {
// method and property signatures
int CalculateSalary();
int MaxSalary { get; } // read only
}
class Worker implements Employee
class Worker : IEmployee
A contract with the compiler:
"this class will define all the methods and
properties specified by the interface"
Multiple inheritance:
•
•
extend one superclass,
implement several interfaces
class Amphibean extends Car
implements IBoat
Worker
IEmployee
Multiple inheritance:
•
•
derive from one base class,
implement several interfaces (with ',')
class Amphibean : Car, IBoat, ISubmarine
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Heilbronn, 23.05.2005
Unterschiede zwischen C# und Java.doc
Seite 6
Ch "Delegates": for passing methods as arguments
10.6
Delegate = class that encapsulates reference(s) to method(s) (see 'command' design pattern)
Receiver of a delegate can call the method contained in the delegate.
Delegate with one method: derive from base class System.Delegate
Delegate with several methods: derive from base class System.MulticastDelegate.
Step 1. Declare delegate with method signature
public delegate bool Comparator(int element1, int element2)
Methods compatible to Comparator must have identical parameters & return type
Step 2: Implement one or several methods compatible to delegate method, e.g.
private bool SortAscending( int element1, int element2 )
{ return element1 > element2; }
private bool SortDescending( int element1, int element2 )
{ return element1 < element2; }
Step 3: Declare Method with delegate method in its arguments that calls the delegate method
public static void SortArray( int[] array, Comparator Compare )
{ ... if Compare(int1, int2) ... }
Step 4: Call this Method passing a delegate instance as an argument
SortArray( elementArray, new Comparator(SortAscending) );
Example: fig. 10.24 - 10.25
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Heilbronn, 23.05.2005
Unterschiede zwischen C# und Java.doc
Seite 7
Ch.
Operator Overloading: (as in C++)
10.11
possible in user defined classes for many unary and binary operators
Example: Complex numbers, overloading +, -, * operators Fig. 10.26 - 10.27
// a = 5+7i, b = 1-8i; compact notation for subtraction wanted:
ComplexNumber c = a – b; // (5+1) + (7-8)I = -2 + 15i, need operator-
Operator Overloads must be public static , take matching number of parameters.
Note: Overloading binary operator+ also overloads unary operator += ! (Own experience)
"C# lässt zu, dass benutzerdefinierte Typen durch Definition statischer Memberfunktionen
und Verwendung des operator-Schlüsselworts Operatoren überladen. Es können jedoch
nicht alle Operatoren überladen werden, und bei anderen bestehen Einschränkungen, wie
in der folgenden Tabelle aufgelistet ist:
Operatoren
Überladbarkeit
+, -, !, ~, ++, --, true, false Diese unären Operatoren können überladen werden.
+, -, *, /, %, &, |, ^, <<, >> Diese binären Operatoren können überladen werden.
==, !=, <, >, <=, >=
Die Vergleichsoperatoren können überladen werden (siehe aber
unten stehenden Hi nweis).
Hinweis Wenn Vergleichoperatoren überladen werden, dann müssen sie paarweise überladen werden, was Folgendes bedeutet: Wird == überladen, dann muss auch != überladen
werden. Das Umgekehrte trifft ebenfalls zu, und Ähnliches gilt für < und > und für <= und
>=. "
(Quelle: Hilfe in MS Visual Studio .NET zu Operator Overloading)
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Heilbronn, 23.05.2005
Unterschiede zwischen C# und Java.doc
Seite 8
Ch.
11
Exception Handling (mostly as in Java) ch. 11.3, fig. 11.1
try {
// normal processing that may cause an exception
}
catch (XxxException e) {
// error handling, may use
// e.ToString(), e.Message, e.StackTrace,
// e.InnerException (original exception before rethrow in catch clause)
}
[ finally {
// cleaning up in any case, release resources
} ]
Throwing an exception:
if (...) throw new XxxException("Exception message")
ch. 11.5, fig. 11.2
Note: unlike Java, a method throwing an uncaught exception does not have a
throws XxxException clause in its signature!
Ch. 11.4: A hierarchy of C# Exceptions exists, starting with Exception.
Application-specific exception classes should be based on ApplicationException,
need three constructors
MyException(), MyException(string message),
MyException(string msg, Exception inner)
all of which use the constructor o f the base exception class
int sum = checked (x + y)
will throw OverflowException
ch. 11.7, fig. 11.4
if overflow for int type occurs (> 2 31 -1)
aus Folien von Mössenböck, Uni Linz (A). aus .ix
Attribute
[Serializable]
class C {...}
// macht C serialisierbar
[Conditional]-Attribut : Neue Gestalt der C-Makros und –Switches
#define debug
// Präprozessor-Anweisung
class C {
[Conditional("debug")]
static void Assert (bool ok, string errorMsg)
{
if (!ok) {
Console.WriteString(errorMsg);
System.Environment.Exit(0);
}
}
Prof. Dr.-Ing. Gerald Permantier, Fachbereich T2, Fachhochschule Heilbronn
Max-Planck-Str. 39, 74081 Heilbronn ) 07131/504- 251/265 4 07131/25 24 70 - [email protected]
Herunterladen