Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Aphorismen
Applications
Business Economics & Admin.
My Computers
Cooking
Devices
Folders
Food
Hardware
Infos
Software Development
Sports
Operation Instructions
Todos
Test
Help
Glossary
Community portal
adaptions
Sidebar anpassen
Wiki RB4
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
JavaLanguage
(section)
Page
Discussion
English
Read
Edit
View history
Toolbox
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Classes== Classes are declared by ['''public'''] ['''abstract'''] ['''final'''] '''class''' <ClassName> '''extends''' <BaseClassName> ['''implements''' <InterfaceName>] '''{''' <Methods> <Attributes|Fields > <ctors> ['''static''' '''{''' <static initialization> '''}'''] '''}''' Class names can be used anywhere primitive data types can be used. Variables have to be defined before using them. Es ist keine Vorwärtsdeklaration innerhalb eines Moduls notwendig. Final classes cannot be parent classes. A class with one or more '''abstract''' methods must itself be declared abstract, also if the class doesn't implement all interface methodes of an extended interface. A class can also be declared as abstract if an instantiation is not useful. Inner classes can even be declared private. The '''static initialization''' is something like a ctor for static attributes. It is called when the class is loaded. There can be variables declared in the static initialization block, there can be even multiple static initialization blocks which are concatenated. Der Compiler überprüft, dass in diesen Blöcken nicht fälschlicherweise Variablen vor ihrer Initialisierung verwendet werden. Diese Überprüfung läßt sich leider umgehen, in dem man statische Methoden in diesen Blöcken aufruft, in denen auf nicht initialisierte member zugegriffen wird (24 page 25). Classes declared as abstract can have methods which have an implementation. They can also have static method which can be called anyway. ===Attributes=== ['''public'''|'''private'''|'''protected'''] ['''static'''|'''final'''|'''transient'''|'''volatile'''] <Type> <MemberName> [ = ...]; Private member without Getter and Setter werden '''field''' bezeichnet. Member with a Getter/Setter pair are called '''property'''. There is a difference while in [[JavaJEEJPA|JPA]] for annotations. For properties the getter is annotated. A '''public''' member is accessible anywhere the class name is accessible. '''Private''' member besagen, dass die nur Methoden dieser Klasse auf sie zugreifen können. A '''protected''' member is throughout the package that contains the class in which the field is declared, and is also also accessible (unless shadowed) within the body of any subclass of that class. Variables may be marked '''transient''' to indicate to low-level parts of the Java virtual machine that they are not part of the persistent state of an object. The default '''package''' visibility (nothing specified) is more restrictive than protected but less restrictive than private. They are only visible by classes in the same package and not even by subclasses of different packages. A variable declared '''volatile''' is known to be modified asynchronously. The compiler arranges to use such variables carefully so that unsynchronized accesses to volatile variables are observed in some global total order. This means that variables which are declared volatile are reloaded from and stored to memory at each use, in a way that is coherent throughout a multiprocessor. Static variables or class variables are declared as '''static'''. They get unlike local variables a default initialization. Class variables are accessed by <Class¬name>.<Va¬riablename>. ====Hidden member==== Members can be hidden durch local variables or parameters of the same name or by members of a subclass with the same name. Such collisions can be resolved using ‘super.’ or ‘this.’ or ‘<Classname>.’ or ‘(<Classname>this).’. Something like ‘super.super.’ is not allowed. Im Unterschied zum Overriding von Methoden kann man von außen durch casts auf die hidden member der Basisklassen zugreifen. Ein weiterer Unterschied ist, daß ein statischer member einen nicht statischen member hiden kann. ===Methods=== ['''public'''|'''private'''|'''protected'''] ['''static'''|'''abstract'''|'''final'''|'''native'''|'''synchronized'''] <Type>|'''void'''|<Type>'''[]''' <MethodName>'''('''<Parameterlist> ['''...'''<ArrayName>]''')''' ['''throws''' <Exception>{''','''<Exception}] {...}; Für den Namen der Methode gibt es keine Beschränkung. Er kann auch wie die Klasse heissen und wird vom ctor nur durch den return type unterschieden. There can be only one method with the same signature. It is also possible to overload a method by using the same name and different parameters. Calling a method is called invoking a method of an object or sending a message to an object. All parameters are passed by value. The value of object parameters and arrays is a reference. To manipulate parameters you have to use objects or arrays. A method can never change the values of their parameters z.B. die Referenz umhängen, so daß diese Änderung den Methodenaufruf überdauert. Methods that change instance fields are called mutator methods and those that only access instance fields are called accessor methods. <Parameterlist> := <Standardlist>|<Type>'''...''' <Varname> Since Java 5 the second is a '''variable argument list'''. <Varname> is always an array and can be used e.g. with the extended for. Beim Aufruf einer Methode kann der return value ignoriert werden d.h. man muss den return value im Code keiner Variablen zuweisen: A.DoSomething(); // der return value von DoSomething() wird ignoriert There is a this member available in every method. The this member can be used to discriminated between a parameter and an attribute e.g. void <Operation>(int x) { this.x = x; } or for ctor calling. There is also a super member to access members or methods of the super class with '''super'''.<MethodName>'''('''<Parameter>''');''' but it is not possible to call the method an indirect base class. ====Static methods==== Static methods or class methods do not operate on objects. You can use them without creating an instance of the object like <ClassName>'''.'''<StaticMethodName>'''('''<Parameter>''');''' ====Final methods==== Final methods can not be overwritten, d.h. Methoden in direkten oder indirekten subclasses mit der gleichen Signatur werden vom Compiler abgelehnt. Reasons can be efficiency (inline) and security (you know what you call). ====Abstract methods==== Abstract methods don’t have a body. If there is at least one abstract method the class must also be declared abstract. ====Native methods==== A method can be declared native, in which case the method is implemented in a platform-dependent way, for example, in C or assembly language. Because the implimentation is not provided by Java Language code, the method declaration contains no body (a semicolon appears instead of a block). Native methods are otherwise like normal Java methods; they are inherited, may be static or not, may be final or not, may override or be overridden by non-native methods, and so on. ====ctors==== ['''public'''|'''private'''|'''protected'''| <ClassName>(<ParameterList>) { ['''this('''<ParameterList>''');'''|'''super('''ParameterList''');'''] <statements>} } A ctor has no return value and it is not allowed to use the return statement with an argument. The compiler decides depending on the parameters which base class ctor is used. If a default ctor (without parameters) is missing, the compiler adds on. If an explicit ctor call for the superclass or for another ctor is missing ‘super();’ is inserted implicitly at the first line, so all ctors are chained. If the base class does not have a ctor without an argument this will lead to a compile error. A call super ( ... ); to a superclass constructor, whether it actually appears as an explicit constructor call statement or is implicitly assumed, performs an additional implicit action after a normal return of control from the superclass constructor: all the instance variables that have initializers are initialized at that time. More precisely: for every instance variable declared in the class containing the call, taken in the order in which the instance variables appear in the class declaration: if that variable has an initializer and either the initialization expression is not a constant expression or its value is not the standard default value for the variable, then the initialization expression is executed and its value is assigned to the instance variable. It is a compile-time error for instance variable initializations to have a forward dependency. Wenn man fälschlicherweise eine Methode mit gleichem Namen wie die Klasse und einem return type definiert, so handelt es sich um eine normale Methode und nicht um einen ctor. Private ctors verhindern, dass eine Klasse angelegt wird (s. Example (w)). A special ctor feature is the possibility to call a different ctor by ctor1(a,b,c) { '''this'''(new X(), a, b, c); // it must be the first line of a ctor } which also must be the first statement in the ctor. A call this(... ); to another constructor in the same class does not perform the mentioned additional implicit action. Bei ctor design ist generell zu beachten, daß subclasses damit zurechtkommen. Man ruft am besten keine privaten Methoden auf, und schreibt am besten immer auch einen parameterlosen ctor und eine Menge von u.U. private Methoden, die die Einzelschritte implementieren (s. 24 page 26). ====Finalize==== Before an object gets garbage-collected, the garbage collector gives the object an opportunity to clean up after itself through a call to the object's finalize method. This process is known as ''finalization. ''The finalize method must be declared as follows and it is good practice to apply the following pattern: protected void finalize() throws Throwable { try { <statements> } finally { super.finalize(); } } There is a great difference between the C++ dtor and the finalize() method in java. The dtor is called when an object is deleted. The finalize() method is called by the garbage collector, so it might be called never. Finalize() methods are not chained automatically but have to be chained explicitly. There the last statement should be <code>super.finalize();</code>. In einem standard java program finalize is not called for the object with the main method (logisch but Java 1.1 had added a static method called runFinalizerOnExit() in the system class that will guarantee the the finalize method is called before java shuts down. Remember that you do not know when it is called. ===object class=== The '''Object class''' is the top of Java's class hierarchy and the parent of everything even if it is not specified in the extension list (but it can be specified there). ===[[JavaNestedClasses|Inner bzw. Nested Classes]]=== ===Inheritance=== '''public''' '''class''' <ClassName> '''extends''' <ClassName> ====Attributes==== Private attributes of the superclass are not visible to the subclass. ====Overriding Methods==== A non-static method defined in a subclass with the same name and paramter list (signature) as a method in one of its ancestors classes overrides the method of the ancestor class from the subclass. Alle Methoden sind virtual. The access modifier of the overriding method must provide at least as much access as the overridden method, which seems a little bit strange. Overriden methods cannot be accessed outside of the class that overrides them. A method with the same signature but different return types or a static method with a the same signature as one of one of the ancestor classes or a non-static method with the same signature as a static method of one of the ancestor classes generates a compiler error. If you have an object of class B which extends class A and which overrides f() it is impossible to call f() of A but in methods of B using super.f(). Finding the correct method is called overloading resolution. '''Final''' methods cannot be overriden. '''Abstract''' methods must be overriden. Überschriebene '''synchronized''' Methoden erben diese Eigenschaft nicht automatisch, sondern müssen ebenfalls als synchronized deklariert werden. Allerdings bleibt die Basisklassen Methode weiterhin synchronisiert. Static methods can not be declared in interfaces, cannot be declared abstract and cannot be overriden (but hidden). class Super { static String greeting() { return "goodnight"; } String name() { return "Richard"; } } class Sub extends Super { static String greeting() { // hidden return "hello"; } String name() { // override return "Dick"; } } Super s = new Sub(); System.out.println(s.greeting() + " " + s.name()); // prints out 'goodnight dick' It’s no problem to ‘override’ private methods because in reality it is no overriding. ===Interfaces=== An interface defines a protocol of behavior. A Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface, thereby agreeing to certain behavior. A class that implements an interface adheres to the protocol defined by that interface. To declare a class that implements an interface, include an implements clause in the class declaration. Your class can implement more than one interface (Java supports multiple interface inheritance), so the implements keyword is followed by a comma-delimited list of the interfaces implemented by the class. '''class''' <ClassName> '''implements''' <Interfaces> { ... } When a class declares that it implements an interface, it's basically signing a contract to the effect that it will provide at least an empty implementations for all of the methods in the interface. An interface is defined by ['''public'''] '''interface''' <InterfaceName> ['''extends''' <SuperInterfaces>] { ['''public abstract'''] <ReturnType> <MethodName>'''('''<ParameterList>''');''' ... ['''public static final'''] <Type> <ConstantName> '''=''' <Value>'''; // '''constants } Der default modifier einer Methode ist public. Es ist ein Fehler wenn Interfaces sich selbst direkt oder indirekt extenden. A method declaration in an interface body may not include any of the modifiers final, native, static, or synchronized. Interfaces können Attribute definieren, die aber immer implicit statisch und final sind und explizit initialisiert werden müssen. Interfaces können auch als Parameter übergeben werden oder als Typ einer lokalen Variablen verwendet werden. Eine andere Verwendung ist folgende: <Interface> <Variable> '''= new''' <ClassWithInterface>'''();''' Interface with no methods are called marker interfaces, because they mark that the class capable of doing something. At this point, many programmers wonder how an interface differs from an abstract class. An interface is simply a list of unimplemented, and therefore abstract, methods. Wouldn't the following Sleeper class do the same thing as the Sleeper interface? abstract class Sleeper { public abstract void wakeUp();} No. The two are not equivalent. If Sleeper is an abstract class, then all objects that wish to use AlarmClock must be instances of a class inherited from Sleeper. However, many objects that wish to use AlarmClock already have a superclass. For example, the GUIClock is an Applet; it must be an applet to run inside a browser. But Java doesn't support multiple inheritance. So GUIClock can't be both a Sleeper and an Applet. Hence, you use an interface instead. This is the practical explanation of the problem. The conceptual explanation is this: AlarmClock should not force a class relationship on its users. It doesn't matter what their class is. It simply matters that they implement a specific method. Often interfaces are touted as an alternative to multiple class inheritance. While interfaces may solve similar problems, interface and multiple class inheritance are quite different animals, in particular: A class inherits only constants from an interface. A class cannot inherit method implementations from an interface. The interface hierarchy is independent of the class hierarchy. Classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance. Yet, Java does allow multiple interface inheritance. That is, an interface can have multiple ''superinterfaces''. You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following: Capturing similarities between unrelated classes without artificially forcing a class relationship Declaring methods that one or more classes are expected to implement Revealing an object's programming interface without revealing its class. (Objects such as these are called ''anonymous objects'' and can be useful when shipping a package of classes to other developers.) ===Properties=== Java definiert eine Reihe von properties wie z.B. user.home oder java.home. Diese können in Applikationen abgefragt werden, werden andererseits aber auch in den Security Files referenziert und legen fest, welche policy files angezogen werden.
Summary:
Please note that all contributions to Wiki RB4 may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Uwe Heuer Wiki New:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Toggle limited content width