锘??xml version="1.0" encoding="utf-8" standalone="yes"?> Many people have heard that you can't override a static method. This is true - you can't. However it is possible to write code like this: This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does. So what's the difference? Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code: If you run this, the output is Why do we get instanceMethod from Bar, but classMethod() from Foo? Aren't we using the same instance f to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior. Since instanceMethod() is (drum roll please...) an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance f to determine which method to run. Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods. With classMethod() though. since (ahem) it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by f) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since f is declared as type Foo, the compiler looks at f.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by f is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism. Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method. So what about accessing a static method using an instance? It's possible in Java to write something like: where f is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance f is not really important here. Only the declared type of f matters. That is, what class is f declared to be? Since classMethod() is static, the class of f (as determined by the compiler at compile time) is all we need. Rather than writing: Barring that, you could always come up with this monstrosity: But all this could be avoided by simply not trying to override your static (class) methods. :-) Why does the compiler sometimes talk about overriding static methods? Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override".. Anders Hejlsberg, a distinguished engineer at Microsoft, led the team that designed the C# (pronounced C Sharp) programming language. Hejlsberg first vaulted onto the software world stage in the early eighties by creating a Pascal compiler for MS-DOS and CP/M. A very young company called Borland soon hired Hejlsberg and bought his compiler, which was thereafter marketed as Turbo Pascal. At Borland, Hejlsberg continued to develop Turbo Pascal and eventually led the team that designed Turbo Pascal's replacement: Delphi. In 1996, after 13 years with Borland, Hejlsberg joined Microsoft, where he initially worked as an architect of Visual J++ and the Windows Foundation Classes (WFC). Subsequently, Hejlsberg was chief designer of C# and a key participant in the creation of the .NET framework. Currently, Anders Hejlsberg leads the continued development of the C# programming language. On July 30, 2003, Bruce Eckel, author of Thinking in C++ and Thinking in Java, and Bill Venners, editor-in-chief of Artima.com, met with Anders Hejlsberg in his office at Microsoft in Redmond, Washington. In this interview, which will be published in multiple installments on Artima.com and on an audio CD-ROM to be released this fall by Bruce Eckel, Anders Hejlsberg discusses many design choices of the C# language and the .NET framework. Bruce Eckel: C# doesn't have checked exceptions. How did you decide whether or not to put checked exceptions into C#? Anders Hejlsberg: I see two big issues with checked exceptions: scalability and versionability. I know you've written some about checked exceptions too, and you tend to agree with our line of thinking. Bruce Eckel: I used to think that checked exceptions were really great. Anders Hejlsberg: Exactly. Frankly, they look really great up front, and there's nothing wrong with the idea. I completely agree that checked exceptions are a wonderful feature. It's just that particular implementations can be problematic. By implementing checked exceptions the way it's done in Java, for example, I think you just take one set of problems and trade them for another set of problems. In the end it's not clear to me that you actually make life any easier. You just make it different. Bruce Eckel: Was there a lot of disagreement in the C# design team about checked excpetions? Anders Hejlsberg: No, I think there was fairly broad agreement in our design group. C# is basically silent on the checked exceptions issue. Once a better solution is known—and trust me we continue to think about it—we can go back and actually put something in place. I'm a strong believer that if you don't have anything right to say, or anything that moves the art forward, then you'd better just be completely silent and neutral, as opposed to trying to lay out a framework. If you ask beginning programmers to write a calendar control, they often think to themselves, "Oh, I'm going to write the world's best calendar control! It's going to be polymorphic with respect to the kind of calendar. It will have displayers, and mungers, and this, that, and the other." They need to ship a calendar application in two months. They put all this infrastructure into place in the control, and then spend two days writing a crappy calendar application on top of it. They'll think, "In the next version of the application, I'm going to do so much more." Once they start thinking about how they're actually going to implement all of these other concretizations of their abstract design, however, it turns out that their design is completely wrong. And now they've painted themself into a corner, and they have to throw the whole thing out. I have seen that over and over. I'm a strong believer in being minimalistic. Unless you actually are going to solve the general problem, don't try and put in place a framework for solving a specific one, because you don't know what that framework should look like. Bruce Eckel: The Extreme Programmers say, "Do the simplest thing that could possibly work." Anders Hejlsberg: Yeah, well, Einstein said that, "Do the simplest thing possible, but no simpler." The concern I have about checked exceptions is the handcuffs they put on programmers. You see programmers picking up new APIs that have all these throws clauses, and then you see how convoluted their code gets, and you realize the checked exceptions aren't helping them any. It is sort of these dictatorial API designers telling you how to do your exception handling. They should not be doing that. Bill Venners: You mentioned scalability and versioning concerns with respect to checked exceptions. Could you clarify what you mean by those two issues? Anders Hejlsberg: Let's start with versioning, because the issues are pretty easy to see there. Let's say I create a method Adding a new exception to a throws clause in a new version breaks client code. It's like adding a method to an interface. After you publish an interface, it is for all practical purposes immutable, because any implementation of it might have the methods that you want to add in the next version. So you've got to create a new interface instead. Similarly with exceptions, you would either have to create a whole new method called Bill Venners: But aren't you breaking their code in that case anyway, even in a language without checked exceptions? If the new version of Anders Hejlsberg: No, because in a lot of cases, people don't care. They're not going to handle any of these exceptions. There's a bottom level exception handler around their message loop. That handler is just going to bring up a dialog that says what went wrong and continue. The programmers protect their code by writing try finally's everywhere, so they'll back out correctly if an exception occurs, but they're not actually interested in handling the exceptions. The throws clause, at least the way it's implemented in Java, doesn't necessarily force you to handle the exceptions, but if you don't handle them, it forces you to acknowledge precisely which exceptions might pass through. It requires you to either catch declared exceptions or put them in your own throws clause. To work around this requirement, people do ridiculous things. For example, they decorate every method with, " Bill Venners: So you think the more common case is that callers don't explicitly handle exceptions in deference to a general catch clause further up the call stack? Anders Hejlsberg: It is funny how people think that the important thing about exceptions is handling them. That is not the important thing about exceptions. In a well-written application there's a ratio of ten to one, in my opinion, of try finally to try catch. Or in C#, Bill Venners: What's in the finally? Anders Hejlsberg: In the finally, you protect yourself against the exceptions, but you don't actually handle them. Error handling you put somewhere else. Surely in any kind of event-driven application like any kind of modern UI, you typically put an exception handler around your main message pump, and you just handle exceptions as they fall out that way. But you make sure you protect yourself all the way out by deallocating any resources you've grabbed, and so forth. You clean up after yourself, so you're always in a consistent state. You don't want a program where in 100 different places you handle exceptions and pop up error dialogs. What if you want to change the way you put up that dialog box? That's just terrible. The exception handling should be centralized, and you should just protect yourself as the exceptions propagate out to the handler. Anders Hejlsberg: The scalability issue is somewhat related to the versionability issue. In the small, checked exceptions are very enticing. With a little example, you can show that you've actually checked that you caught the In the large, checked exceptions become such an irritation that people completely circumvent the feature. They either say, " And so, when you take all of these issues, to me it just seems more thinking is needed before we put some kind of checked exceptions mechanism in place for C#. But that said, there's certainly tremendous value in knowing what exceptions can get thrown, and having some sort of tool that checks. I don't think we can construct hard and fast rules down to, it is either a compiler error or not. But I think we can certainly do a lot with analysis tools that detect suspicious code, including uncaught exceptions, and points out those potential holes to you.
Can I override a static method?
class Foo {
public static void method() {
System.out.println("in Foo");
}
}
class Bar extends Foo {
public static void method() {
System.out.println("in Bar");
}
}
class Foo {
public static void classMethod() {
System.out.println("classMethod() in Foo");
}
public void instanceMethod() {
System.out.println("instanceMethod() in Foo");
}
}
class Bar extends Foo {
public static void classMethod() {
System.out.println("classMethod() in Bar");
}
public void instanceMethod() {
System.out.println("instanceMethod() in Bar");
}
}
class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.instanceMethod();
f.classMethod();
}
}instanceMethod() in Bar classMethod() in Foo
f.classMethod();
f.classMethod();
It would be better coding style to write either: Foo.classMethod();
or Bar.classMethod();
That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method. f.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);
ref: http://www.coderanch.com/how-to/java/OverridingVsHiding
]]>
http://www.stormpath.com/blog/spring-mvc-rest-exception-handling-best-practices-part-2
]]>
Anders Hejlsberg, the lead C# architect, talks with Bruce Eckel and Bill Venners about versionability and scalability issues with checked exceptions.Remaining Neutral on Checked Exceptions
Versioning with Checked Exceptions
foo
that declares it throws exceptions A
, B
, and C
. In version two of foo
, I want to add a bunch of features, and now foo
might throw exception D
. It is a breaking change for me to add D
to the throws clause of that method, because existing caller of that method will almost certainly not handle that exception.foo2
that throws more exceptions, or you would have to catch exception D
in the new foo
, and transform the D
into an A
,B
, or C
.foo
is going to throw a new exception that clients should think about handling, isn't their code broken just by the fact that they didn't expect that exception when they wrote the code?throws Exception
." That just completely defeats the feature, and you just made the programmer write more gobbledy gunk. That doesn't help anybody.using
statements, which are like try finally.The Scalability of Checked Exceptions
Bill Venners: What is the scalability issue with checked exceptions?FileNotFoundException
, and isn't that great? Well, that's fine when you're just calling one API. The trouble begins when you start building big systems where you're talking to four or five different subsystems. Each subsystem throws four to ten exceptions. Now, each time you walk up the ladder of aggregation, you have this exponential hierarchy below you of exceptions you have to deal with. You end up having to declare 40 exceptions that you might throw. And once you aggregate that with another subsystem you've got 80 exceptions in your throws clause. It just balloons out of control.throws Exception
," everywhere; or—and I can't tell you how many times I've seen this—they say, "try, da da da da da, catch curly curly
." They think, "Oh I'll come back and deal with these empty catch clauses later," and then of course they never do. In those situations, checked exceptions have actually degraded the quality of the system in the large.
from: http://www.artima.com/intv/handcuffs.html
This list is not complete, and your input is appreciated.
Concept/Language Construct | Java 5.0 | ActionScript 3.0 |
Class library packaging | .jar | .swc |
Inheritance | class Employee extends Person{…} | class Employee extends Person{…} |
Variable declaration and initialization | String firstName=”John”; Date shipDate=new Date(); int i; int a, b=10; double salary; | var firstName:String=”John”; var shipDate:Date=new Date(); var i:int; var a:int, b:int=10; var salary:Number; |
Undeclared variables | n/a | It’s an equivalent to the wild card type notation *. If you declare a variable but do not specify its type, the * type will apply. A default value: undefined var myVar:*; |
Variable scopes | block: declared within curly braces, member: declared on the class level no global variables | No block scope: the minimal scope is a function local: declared within a function member: declared on the class level If a variable is declared outside of any function or class definition, it has global scope. |
Strings | Immutable, store sequences of two-byte Unicode characters | Immutable, store sequences of two-byte Unicode characters |
Terminating statements with semicolons | A must | If you write one statement per line you can omit it. |
Strict equality operator | n/a | === for strict non-equality use !== |
Constant qualifier | The keyword final final int STATE=”NY”; | The keyword const const STATE:int =”NY”; |
Type checking | Static (checked at compile time) | Dynamic (checked at run-time) and static (it’s so called ‘strict mode’, which is default in Flex Builder) |
Type check operator | instanceof | is – checks data type, i.e. if (myVar is String){…} The is operator is a replacement of older instanceof |
The as operator | n/a | Similar to is operator, but returns not Boolean, but the result of expression: var orderId:String=”123”; var orderIdN:Number=orderId as Number; trace(orderIdN);//prints 123 |
Primitives | byte, int, long, float, double,short, boolean, char | all primitives in ActionScript areobjects. The following lines are equivalent; var age:int = 25; var age:int = new int(25); |
Complex types | n/a | Array, Date, Error, Function, RegExp, XML, and XMLList |
Array declaration and instantiation | int quarterResults[]; quarterResults = int quarterResults[]={25,33,56,84}; | var quarterResults:Array or var quarterResults:Array=[]; var quarterResults:Array= AS3 also has associative arrays that uses named elements instead of numeric indexes (similar to Hashtable). |
The top class in the inheritance tree | Object | Object |
Casting syntax: cast the class Object to Person: | Person p=(Person) myObject; | var p:Person= Person(myObject); or var p:Person= myObject as Person; |
upcasting | class Xyz extends Abc{} Abc myObj = new Xyz(); | class Xyz extends Abc{} var myObj:Abc=new Xyz(); |
Un-typed variable | n/a | var myObject:* var myObject: |
packages | package com.xyz; class myClass {…} | package com.xyz{ class myClass{…} } ActionScript packages can include not only classes, but separate functions as well |
Class access levels | public, private, protected if none is specified, classes have package access level | public, private, protected if none is specified, classes haveinternal access level (similar to package access level in Java) |
Custom access levels: namespaces | n/a | Similar to XML namespaces. namespace abc; abc function myCalc(){} or abc::myCalc(){} use namespace abc ; |
Console output | System.out.println(); | // in debug mode only trace(); |
imports | import com.abc.*; import com.abc.MyClass; | import com.abc.*; import com.abc.MyClass; packages must be imported even if the class names are fully qualified in the code. |
Unordered key-value pairs | Hashtable, Map Hashtable friends = new Hashtable(); friends.put(“good”, friends.put(“best”, friends.put(“bad”, String bestFriend= friends.get(“best”); // bestFriend is Bill | Associative Arrays Allows referencing its elements by names instead of indexes. var friends:Array=new Array(); friends["best"]=”Bill”; friends["bad"]=”Masha”; var bestFriend:String= friends[“best”] friends.best=”Alex”; Another syntax: var car:Object = {make:”Toyota”, model:”Camry”}; trace (car["make"], car.model); // Output: Toyota Camry |
Hoisting | n/a | Compiler moves all variable declarations to the top of the function, so you can use a variable name even before it’s been explicitly declared in the code. |
Instantiation objects from classes | Customer cmr = new Customer(); Class cls = Class.forName(“Customer”); Object myObj= cls.newInstance(); | var cmr:Customer = new Customer(); var cls:Class = flash.util.getClassByName(“Customer”); |
Private classes | private class myClass{…} | There is no private classes in AS3. |
Private constructors | Supported. Typical use: singleton classes. | Not available. Implementation of private constructors is postponed as they are not the part of the ECMAScript standard yet. To create a Singleton, use public static getInstance(), which sets a private flag instanceExists after the first instantiation. Check this flag in the public constructor, and if instanceExists==true, throw an error. |
Class and file names | A file can have multiple class declarations, but only one of them can be public, and the file must have the same name as this class. | A file can have multiple class declarations, but only one of them can be placed inside the package declaration, and the file must have the same name as this class. |
What can be placed in a package | Classes and interfaces | Classes, interfaces, variables, functions, namespaces, and executable statements. |
Dynamic classes (define an object that can be altered at runtime by adding or changing properties and methods). | n/a | dynamic class Person { var name:String; } //Dynamically add a variable // and a function var p:Person = new Person(); p.name=”Joe”; p.age=25; p.printMe = function () { trace (p.name, p.age); } p.printMe(); // Joe 25 |
function closures | n/a. Closure is a proposed addition to Java 7. | myButton.addEventListener(“click”, myMethod); A closure is an object that represents a snapshot of a function with its lexical context (variable’s values, objects in the scope). A function closure can be passed as an argument and executed without being a part of any object |
Abstract classes | supported | n/a |
Function overriding | supported | Supported. You must use the override qualifier |
Function overloading | supported | Not supported. |
Interfaces | class A implements B{…} interfaces can contain method declarations and final variables. | class A implements B{…} interfaces can contain only function declarations. |
Exception handling | Keywords: try, catch, throw, finally, throws Uncaught exceptions are propagated to the calling method. | Keywords: try, catch, throw, finally A method does not have to declare exceptions. Can throw not only Error objects, but also numbers: throw 25.3; Flash Player terminates the script in case of uncaught exception. |
Regular expressions | Supported | Supported |
What is Shallow Copy?
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
In this figure, the MainObject1 have fields "field1" of int type, and "ContainObject1" of ContainObject type. When you do a shallow copy of MainObject1, MainObject2 is created with "field3" containing the copied value of "field1" and still pointing to ContainObject1 itself. Observe here and you will find that since field1 is of primitive type, the values of it are copied to field3 but ContainedObject1 is an object, so MainObject2 is still pointing to ContainObject1. So any changes made to ContainObject1 in MainObject1 will reflect in MainObject2.
Now if this is shallow copy, lets see what's deep copy?
What is Deep Copy?
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
In this figure, the MainObject1 have fields "field1" of int type, and "ContainObject1" of ContainObject type. When you do a deep copy of MainObject1, MainObject2 is created with "field3" containing the copied value of "field1" and "ContainObject2" containing the copied value of ContainObject1.So any changes made to ContainObject1 in MainObject1 will not reflect in MainObject2.
Well, here we are with what shallow copy and deep copy are and obviously the difference between them. Now lets see how to implement them in java.
How to implement shallow copy in java?
Here is an example of Shallow Copy implementation
How to implement deep copy in java?
Here is an example of Deep Copy implementation. This is the same example of Shallow Copy implementation and hence I didnt write the Subject and CopyTest classes as there is no change in them.
Well, if you observe here in the "Student" class, you will see only the change in the "clone()" method. Since its a deep copy, you need to create an object of the cloned class. Well if you have have references in the Subject class, then you need to implement Cloneable interface in Subject class and override clone method in it and this goes on and on.
There is an alternative way for deep copy.
Yes, there is. You can do deep copy through serialization. What does serialization do? It writes out the whole object graph into a persistant store and read it back when needed, which means you will get a copy of the whole object graph whne you read it back. This is exactly what you want when you deep copy an object. Note, when you deep copy through serialization, you should make sure that all classes in the object's graph are serializable. Let me explain you this alternative way with an example.
In this example, I have created a ColoredCircle object, c1 and then serialized it (write it out to ByteArrayOutputStream). Then I deserialed the serialized object and saved it in c2. Later I modified the original object, c1. Then if you see the result, c1 is different from c2. c2 is deep copy of first version of c1. So its just a copy and not a reference. Now any modifications to c1 wont affect c2, the deep copy of first version of c1.
Well this approach has got its own limitations and issues:
As you cannot serialize a transient variable, using this approach you cannot copy the transient variables.
Another issue is dealing with the case of a class whose object's instances within a virtual machine must be controlled. This is a special case of the Singleton pattern, in which a class has only one object within a VM. As discussed above, when you serialize an object, you create a totally new object that will not be unique. To get around this default behavior you can use the readResolve() method to force the stream to return an appropriate object rather than the one that was serialized. In this particular case, the appropriate object is the same one that was serialized.
Next one is the performance issue. Creating a socket, serializing an object, passing it through the socket, and then deserializing it is slow compared to calling methods in existing objects. I say, there will be vast difference in the performance. If your code is performance critical, I suggest dont go for this approach. It takes almost 100 times more time to deep copy the object than the way you do by implementing Clonable interface.
When to do shallow copy and deep copy?
Its very simple that if the object has only primitive fields, then obviously you will go for shallow copy but if the object has references to other objects, then based on the requiement, shallow copy or deep copy should be chosen. What I mean here is, if the references are not modified anytime, then there is no point in going for deep copy. You can just opt shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement.
Finally lets have a word about rarely used option - Lazy copy
A lazy copy is a combination of both shallow copy and deep copy. When initially copying an object, a (fast) shallow copy is used. A counter is also used to track how many objects share the data. When the program wants to modify the original object, it can determine if the data is shared (by examining the counter) and can do a deep copy at that time if necessary.
Lazy copy looks to the outside just as a deep copy but takes advantage of the speed of a shallow copy whenever possible. It can be used when the references in the original object are not modified often. The downside are rather high but constant base costs because of the counter. Also, in certain situations, circular references can also cause problems.
TreeSet | HashSet | LinkedHashSet |
|
|
|
unique values | unique values | Unique values |
It stores its elements in a red-black tree | It stores its elements in a hash table | is implemented as a hash table with a linked list running through it |
Order : ascending order | undefined | insertion order |
Performance : Slow | better than LinkedHashSet | has fast adding to the start of the list, and fast deletion from the interior via iteration |
operations (add , remove and contains ) | operations (add, remove, contains and size) | operations (add, contains and remove) |
add, addAll,ceiling,clear,clone,comparator,contains, descendingIterator,descendingSet,first,floor, hashSet,higher,isEmpty,iterator,last,lower,pollFirst, remove,size,subSet,tailSet | add, clear, clone, contains, isEmpty,iterator, remove, size | add, clear, clone, contains, isEmpty,iterator, remove, size |
From AbstractSet:equals, hashCode, removeAll | equals, hashCode, removeAll | equals, hashCode, removeAll |
containsAll, retainAll, toArray, toArray,toString | AbstractCollection:addAll, containsAll, retainAll, toArray,toArray, toString | addAll, containsAll, retainAll, toArray,toArray, toString |
Set:containsAll, equals, hashCode, removeAll,retainAll, toArray, toArray | addAll, containsAll, equals, hashCode,removeAll, retainAll, toArray, toArray | add, addAll, clear, contains, containsAll,equals, hashCode, isEmpty, iterator, remove,removeAll, retainAll, size, toArray, toArray |