Die Präsentation wird geladen. Bitte warten

Die Präsentation wird geladen. Bitte warten

C# versus Java Hanspeter Mössenböck Universität Linz Institut für Praktische Informatik (Systemsoftware) moessenboeck@ssw.uni-linz.ac.at.

Ähnliche Präsentationen


Präsentation zum Thema: "C# versus Java Hanspeter Mössenböck Universität Linz Institut für Praktische Informatik (Systemsoftware) moessenboeck@ssw.uni-linz.ac.at."—  Präsentation transkript:

1 C# versus Java Hanspeter Mössenböck Universität Linz Institut für Praktische Informatik (Systemsoftware)

2 Der Kontext Java-Technologie .NET-Technologie Entstehungsjahr
Betriebssysteme Leitidee VM Zwischencode JIT-Compilation Komponenten Versionierung Applets Datenbanken Web-Programmierung 1995 Unix/Linux, Windows, MacOS, ... Eine Sprache auf vielen Plattformen Java-VM Java-Bytecodes per Methode Beans, EJB - ja JDBC Servlets, JSP 2002 Windows (Linux, MacOS X) Viele Sprachen auf einer Plattform (VB, C++, J#, Eiffel, Fortran, ...) Common Language Runtime Common Intermediate Language gesamt Assemblies ja - ADO.NET ASP.NET

3 Merkmale von C# Sehr ähnlich zu Java Wie in Java Wie in C++
70% Java, 10% C++, 10% Visual Basic, 10% neu Wie in Java Objektorientierung (einf. Vererbung) Interfaces Exceptions Threads Namespaces (wie Packages) Strenge Typprüfung Garbage Collection Reflection Dynamisches Laden von Code ... Wie in C++ (Operator) Overloading Zeigerarithmetik in Unsafe Code Einige syntaktische Details Überblick

4 Neue Features in C# Wirklich neu (vs. Java) "Syntactic Sugar"
Referenzparameter Objekte am Stack (Structs) Blockmatrizen Enumerationen Uniformes Typsystem goto Systemnahes Programmieren Versionierung Attribute Kompatibel mit anderen .NET-Sprachen "Syntactic Sugar" Komponentenunterstützung - Properties - Events Delegates Indexers Operator Overloading foreach-Iterator Boxing/Unboxing ... Überblick

5 Typsystem von C# Typen Werttypen Referenztypen Einfache Typen Enums
Structs Klassen Interfaces Arrays Delegates bool char sbyte short int long byte ushort uint ulong float double decimal Benutzerdefinierbare Typen Alle Typen sind kompatibel mit object - können object-Variablen zugewiesen werden - verstehen object-Operationen

6 Boxing und Unboxing Java 1.4
Auch Werttypen (int, struct, enum) sind zu object kompatibel! Boxing Bei der Zuweisung object obj = 3; wird der Wert 3 in ein Heap-Objekt eingepackt Unboxing int x = (int) obj; wird der eingepackte int-Wert wieder ausgepackt Java 1.4 Object obj = new Integer(3); obj 3 int x = ((Integer)obj).intValue();

7 Klassen und Vererbung C# Java class A { private int x;
public void Foo() {...} public A(int x) { this.x = x; } } class A { private int x; public void Foo() {...} public A(int x) { this.x = x; } } class B : A, I1, I2 { private int y; public int Bar() { ...} public B(int x, int y) : base(x) { this.y = y; } class B extends A implements I1, I2 { public B(int x, int y) { super(x);

8 Überschreiben von Methoden
Java class A { ... public virtual void Foo() { ...} } class A { ... public void Foo() { ...} } class B : A { ... public override void Foo() { base.Foo(); } class B extends A { ... public void Foo() { super.Foo(); }

9 Properties Syntaktische Kurzform für get/set-Methoden
class Data { FileStream s; public string FileName { set { s = new FileStream(value, FileMode.Create); } get { return s.Name; Wird wie ein Feld benutzt ("smart fields") Data d = new Data(); d.FileName = "myFile.txt"; // ruft d.set("myFile.txt") auf string s = d.FileName; // ruft d.get() auf Typ des Properties Name des Properties "Eingangsparameter" von set

10 Properties (Fortsetzung)
get oder set kann fehlen class Account { long balance; public long Balance { get { return balance; } } x = account.Balance; // ok account.Balance = ...; // verboten Nutzen von Properties read-only und write-only-Daten möglich. Validierung beim Zugriff möglich. Benutzersicht und Implementierung der Daten können verschieden sein.

11 Indexer Programmierbarer Operator zum Indizieren einer Folge (Collection) class File { FileStream s; public int this [int index] { get { s.Seek(index, SeekOrigin.Begin); return s.ReadByte(); } set { s.Seek(index, SeekOrigin.Begin); s.WriteByte((byte)value); Benutzung File f = ...; int x = f[10]; // ruft f.get(10) f[10] = 'A'; // ruft f.set(10, 'A') Typ des indi- zierten Ausdrucks Name (immer this) Typ und Name des Indexwerts

12 C# ist oft griffiger als Java
Hashtable tab = new Hashtable(); ... tab["John"] = 123; int x = (int) tab["John"]; Hashtable tab = new Hashtable(); ... tab.put("John", new Integer(123)); int x = ((Integer) tab.get("John")).intValue(); String s = ...; ... for (int i = 0; i < s.Length; i++) process(s[i]); String s = ..; ... for (int i = 0; i < s.length(); i++) process(s.charAt(i)); foreach (char ch in s) process(ch);

13 Ausnahmebehandlung (Exceptions)
Java try { ... ... throw myException; } catch (E1 e) { } catch (E2) { } catch { } finally { } try { ... ... throw myException; } catch (E1 e) { } catch (E2 e) { } catch (Throwable e) { } finally { }

14 Keine Checked Exceptions in C#
Java void Foo() { try { if (...) throw new E1(); else throw new E2(); ... } catch (E1 e) { } void Foo() throws E2 { try { if (...) throw new E1(); else throw new E2(); ... } catch (E1 e) { } Keine Checked Exceptions Wenn keiner der Rufer E2 abfängt, bricht das Programm mit einem Laufzeitfehler ab. Checked Exceptions Ausnahmen müssen abgefangen oder mit throws im Methodenkopf spezifiziert werden.

15 Checked Exceptions Pro Kontra + Dokumentation für den Programmierer
+ Zwingt dazu, jeden Fehlerfall zu bedenken void P() { try { ... Q(); ... } catch (E e) {...} } void Q() throws E { ... R(); ... void R() throws E { ... S(); ... void S() throws E { ... throw new E(); Kontra - Mühsam, wenn Ausnahme weitergereicht wird try { ... } catch (E e) {} Fehler wird verschluckt! - Verführt zu folgendem "Hack"

16 Delegate = Methodentyp
Deklaration eines Delegate-Typs delegate void Notifier (string sender); // normale Methodensignatur // mit Schlüsselwort delegate Deklaration einer Delegate-Variablen Notifier notify; Zuweisung einer Methode an eine Delegate-Variable void SayHello(string sender) { Console.WriteLine("Hello " + sender); } notify = new Notifier(SayHello); Aufruf der Delegate-Variablen notify("Max"); // Aufruf von SayHello("Max") => "Hello Max" void SayGoodBye(string sender) { Console.WriteLine("Good bye " + sender); } notify = new Notifier(SayGoodBye);

17 Multicast-Delegates Delegate-Variable kann mehrere Werte gleichzeitig aufnehmen Notifier notify; notify = new Notifier(SayHello); notify += new Notifier(SayGoodBye); notify("Max"); // "Hello Max" // "Good bye Max" notify -= new Notifier(SayHello); notify("Max"); // "Good bye Max"

18 Threads C# Java Beliebige Methode kann als Thread gestartet werden
void P() { ... thread actions ... } Thread t = new Thread(new ThreadStart(P)); t.Start(); class MyThread extends Thread { public void run() { ... thread actions ... } Thread t = new MyThread(); t.start(); Beliebige Methode kann als Thread gestartet werden Keine Unterklasse von Thread nötig Thread-Aktionen müssen in einer run-Methode stecken Unterklasse von Thread nötig, bzw. Implementierung von Runnable

19 Thread-Synchronisation
Java class Buffer { int[] data; public void Put(int x) { lock(this) { ... } [MethodImpl(MethodImplOptions.Synchronized)] public int Get() { class Buffer { int[] data; public void put(int x) { synchronized(this) { ... } public synchronized int get() { Monitor.Wait(this); Monitor.Pulse(this); Monitor.PulseAll(this); wait(); notify(); notifyAll();

20 Attribute Benutzerdefinierte Informationen über Programmelemente
Können an Typen, Felder, Methoden, etc. angehängt werden. Werden als Metadaten gespeichert. Können zur Laufzeit abgefragt werden. Sind Unterklassen von System.Attribute. Beispiel [Serializable] class C {...} // macht C serialisierbar Mehrfache Attribute zuweisbar [Serializable] [Obsolete] class C {...} [Serializable, Obsolete]

21 Beispiel: [Conditional]-Attribut
Für bedingte Aufrufe von Methoden #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); } static void Main (string[] arg) { Assert(arg.Length > 0, "no arguments specified"); Assert(arg[0] == "...", "invalid argument"); ... Assert wird nur aufgerufen, wenn debug definiert wurde.

22 J# - Java unter .NET Vollständige Java-Syntax (JDK 1.1.4), ähnlich J++
Delegates wie in C# Unterstützt die meisten Java-Bibliotheken (nicht RMI, JNI) Unterstützt die meisten .NET-Bibliotheken (ASP.NET, ADO.NET, Windows Forms) Kann unter Visual Studio.NET verwendet werden Erzeugt keine Java-Bytecodes sondern .NET-Assemblies => nicht portabel, keine Applets

23 Was bringt die Zukunft? Generische Typen C# 2.0 Java 1.5
class Stack<T> { void Push(T x) {...} T Pop() {...} ... } class Stack<T> { void Push(T x) {...} T pop() {...} ... } Stack<int> s = new Stack<int>(); ... int x = s.Pop(); Stack<String> s = new Stack<String>(); ... String x = s.pop(); Erzeugt neue Klasse Stack_int Keine Casts zur Laufzeit Erzeugt keine neue Klasse Stack-Elemente als Objects gespeichert Versteckte Casts zur Laufzeit Keine primitiven Typen (int, char, ...) als Typparameter erlaubt!

24 Java 1.5 holt auf ... Boxing / Unboxing in C# Enumerationen
Object obj = 3; int x = obj; // kein Cast nötig! Object obj = 3; int x = (int) obj; Enumerationen enum Color {red, blue, green} ... if (color == Color.red) ... Spezielle for-Schleife ( foreach) for (Object s : collection) System.out.println((String)s); foreach (string s in collection) Console.WriteLine(s); Metadaten ( Attribute) Author { String name(); } ... @Author(name = "HM") public void foo() {...} public class Author : Attribute { string _name; public string Name { set {_name = value; } } [Author(Name = "HM")] public void Foo() {...}

25 C# 2.0 führt neue Features ein ...
Anonyme Methoden Iteratoren public class Stack { private int[] data; private int top; public void Push(int x) {...} public int Pop() {...} ... public IEnumerator GetEnumerator() { for (int i = 0; i < top; i++) yield return data[i]; } Stack stack = new Stack(); foreach (int x in stack) Console.WriteLine(x); delegate void Notifier (string s); ... Notifier var = delegate (string s) { Print("I got an " + s); } Partielle Typen public partial class A { // in Datei X.cs public void Foo() {...} ... } public partial class A { // in Datei Y.cs public void Bar() {...}

26 Zusammenfassung C# Java mächtiger bequemer und griffiger flexibler
Structs, Referenzparameter, Attribute, ... bequemer und griffiger Indexer, Delegates, ... flexibler erlaubt Systemprogrammierung besser unter Windows kleiner und einfacher größere Verbreitung strikter Checked Exceptions, kein Unsafe Code portabler

27 Danke für Ihre Aufmerksamkeit
Folien unter Beer, Bringruber, Mössenböck, Wöß: Die .NET-Technologie dpunkt.verlag, 2002 Mössenböck: Softwareentwicklung mit C# dpunkt.verlag, 2003


Herunterladen ppt "C# versus Java Hanspeter Mössenböck Universität Linz Institut für Praktische Informatik (Systemsoftware) moessenboeck@ssw.uni-linz.ac.at."

Ähnliche Präsentationen


Google-Anzeigen