General Java Questions - III

General Java Questions - III

Q: I propose that Java should allow multiple inheritance if...Everyone knows the potential problem with multiple inheritance is when you run into theproblem of having two instances of a grand parent super class.For example:class A extends D {int i; }class B extends D {int i; }class C extends A,B {}Potentially, you could have two copies of D for each instance of C.However, I propose that Java should allow multiple inheritance if there are no instancevariables associated with the abstracts that the base class is extending.abstract class A { public setX(); public setY(); public setAll() {setX (); setY(); }abstract class B { public setC(); public setD(); public setBoth(){setC(); setD(); }class C extends A,B {}You won't have two instances of some grandfather class, since A and B doesn't have instancesvariables.I hope the next versions of Java explores this issue.file:///C|/330_new/330_new/general_java-III.htm (1 of 7) [2003-07-22 22:07:55]General Java Questions IIIAnswer: It does. They're called interfaces:interface A { public void setX(); public void setY(); public void setAll(); }interface B { public void setC(); public void setD(); public void setBoth(); }interface C extends A,B {};public abstract class D implements C {}--jimQ: Can I access a private variable of one Object from another Object?Answer: Yes, if this object of the same class. You can access private field from static method ofthe class through an instance of the same class.Check one example below:public class Example {private int privateVar;Example(int a) {privateVar = a;System.out.println("private privateVar = " + privateVar);}public static void main(String[] args) {Example ex = new Example(5);System.out.println(ex.privateVar);}}--AP (JA)Q: Is there a way to know from class X which class called the method foo()?If class A and class B are calling a method foo() on class X, is there a way to know from class Xwhich class called the method foo() (they can be either A or B). I know that this can be done bycapturing the stack trace and examining it, but that solution looks expensive as I have to createa new Throwable object every time and capture stack trace (And I do this quite frequently).Is there any other elegant solution to do this, any help and directionis appreciated.Answer: Pass a reference to the class to the foo() method.foo(Object x){file:///C|/330_new/330_new/general_java-III.htm (2 of 7) [2003-07-22 22:07:55]General Java Questions IIISystem.out.println(x.getClass());}should do it.Q: Is it possible to stop an object from being created during construction?For example if an error occurs inside the constructor (e.g. the parameters pass in were invalid)and I wanted to stop an object being created would it be possible to return null rather than areference to a new object. (I know the term return is technically correct in this case but youknow what I mean).Basically, is it possible to cancel object creation?Answer: Yes, have the constructor throw an exception. Formally, an object _will_ be created(since the constructor is a method invoked after the actual method creation), but nothing usefulwill be returned to the program, and the dead object will be later reclaimed by GarbageCollector.But the clean way is as another reply suggests, that you leave calls to the constructor to a staticfactory method which can check the parameters and return null when needed.Note that a constructor - or any method in general - throwing an exception will not "return null",but will leave the "assign target" as it was.Tor Iver WilhelmsenQ: suppose I put a file a.txt in package com.xyz and the try access it like following. Will itwork?import com.xyz.*;public class Hello{File f = new File("a.txt");...}it is not working for me. Is there any workaround?Answer: If the source and the text file are in the jar file, then you access the file by:URL fileURL = getClass().getResource("file.txt");You can then read the file by using a reader (or whatever you choose),e.g.:_istream = new BufferedReader( newInputStreamReader(fileURL.openStream()) );--file:///C|/330_new/330_new/general_java-III.htm (3 of 7) [2003-07-22 22:07:55]General Java Questions IIIj o h n e w e b e rOr, simplergetClass().getResourcesAsStream("file.txt"), but you must be sure thatfile is in the same directory ( package ) as your class, otherwise youneed play with getClassLoader().getResourceAsStream( "/file.txt" );--OlegQ: Difference between loading and instantiating a class???Well, the subject says it all. What is the difference between loading and instantiating a class ina JVM.Second question: What would happen if at runtime I update a class file? Will the JVM know to use thatinstead?Answer: The difference is that when a class is loaded by a ClassLoader it is read in as a streamof bytes, presumably from a file, but it could just as easily be from over the network, and thenprocessed or "cooked" into a representation that the VM can use to make instances of Objectsof that classes type. This last part is the instantiation. You can load a class at runtime with:Class.forName( "MyClass" );and instantiate one with:MyClass mc = Class.forName( "MyClass" ).newInstance();Cool, ehh. You don't have to know the name of a class at compile time.>Second question: What would happen if at runtime I update a class file?>Will the JVM know to use that instead?Loaded classes are cached because it's quite costly to do the "cooking" I mentioned above. Soit will not be loaded. You may create a separate ClassLoader with new SecureClassLoader butthat will cause all classes _it_ loads to be loaded from this new ClassLoader but that's not whatyou want.I don't know if you can specify that a class should be loaded from disk again using the normalClassLoader. You could very easily make your own ClassLoader in which case you would haveexplicit control over such things. Look at java.lang.ClassLoader and java.lang.Class.--Michael B. Allenfile:///C|/330_new/330_new/general_java-III.htm (4 of 7) [2003-07-22 22:07:55]General Java Questions IIIQ: Why developers should not write programs that call 'sun' packages?Answer: Java Software supports into the future only classes in java.* packages, not sun.*packages. In general, API in sun.* is subject to change at any time without notice.A Java program that directly calls into sun.* packages is not guaranteed to work on all Javacompatibleplatforms. In fact, such a program is not guaranteed to work even in future versionson the same platform.For these reasons, there is no documentation available for the sun.* classes. Platformindependenceis one of the great advantages of developing in the Java programminglanguage. Furthermore, Sun and our licensees of Java technology are committed tomaintaining backward compatibility of the APIs for future versions of the Java platform. (Exceptfor code that relies on serious bugs that we later fix.) This means that once your program iswritten, the class files will work in future releases.For more details, see the article Why Developers Should Not Write Programs That Call 'sun'Packages.http://java.sun.com/products/jdk/faq/faq-sun-packages.htmlQ: Can garbage collector remove my singleton?A usually singleton..public class Single{private static Single single;private Single {}public static Single getInstance(){if(single==null){single = new Single();}return single;}}Well,, seems good ?But classes are objects too...so do Java 2 v1.3 class garbagecollecting? Meaning my singletoncould dissapear if i dont keep a refrence to it (or the class itself) somewhere ?If classes is not garbagecollected, that's pretty stupid, I dont want classes taking up memorywhen i perhaps never will use it again....Answer: No. Classes can define objects. That is, only the dynamic part of the class definesobjects. The static part exists only in one place in memory and can not be duplicated. You cancall the getInstance() method from anywhere in your program.Java requires however that you tell where to find the method, in this case in the Single class.Therefore, you should useSingle.getInstance()file:///C|/330_new/330_new/general_java-III.htm (5 of 7) [2003-07-22 22:07:55]General Java Questions IIIto get the instance. This is (though it looks much like it) not an execution of a method on anobject, but just a method call without object. Single is only used to find out which getInstance()method should be used, and where it is.You could add a delete() method if you don't need the instance anymore:public class Single{private static Single single;private Single {}public static Single getInstance(){if(single==null)single = new Single();return single;}public static delete(){single = null;}}The garbage collector can now remove the single object after delete() is called if memory isneeded.--Rijk-Jan van HaaftenDept of Computer Science, Utrecht University, The NetherlandsP.S by John:Doing more deeper investigation of this question I found one very good article about this topic.Everybody who are interested can read full article here:http://developer.java.sun.com/developer/technicalArticles/Programming/singletons/For the rest of our audience shortly:A Singleton class can be garbage collected and when".. a Singleton class is garbage-collected and then reloaded, a new Singleton instance iscreated. Any class can be garbage-collected when no other object holds reference to the classor its instances. If no object holds a reference to the ' Singleton object, then the Singleton classmay disappear, later to be reloaded when the Singleton is again needed. In that case, a newSingleton object will be created. Any static or instancefields saved for the object will be lost and reinitialized.This problems exists in older JavaTM Virtual Machines1. JDK 1.2 VMs, in particular, conform toa newer class garbage collection model that forbids any class in a given classloader to becollected until all are unreferenced"And you "... can also set your VM to have no class garbage collection (-Xnoclassgc on the JRE1.3, or -noclassgc on the IBM JVM). Keep in mind that if you have a long-running program thatfrequently reloads classes (perhaps through special classloaders such as the remote class loaders), you have to consider whether that could cause afile:///C|/330_new/330_new/general_java-III.htm (6 of 7) [2003-07-22 22:07:55]General Java Questions IIIproblematic buildup of garbage classes in the VM."Also some people asked what is a Singleton and what is relation has it to Java.Shortly a Singleton is one of classical design patterns that are used in software development.More please read in free book here:http://www.patterndepot.com/put/8/JavaPatterns.htmQ: I study patterns now and would be lost and forget everything very soon! Help!I am very new to design patterns and just bought the GoF book to learn about it.But as I complete the first couple of chapters right away, I see that they have 23 differentpatterns and I would be lost and forget everything very soon if I sequentially (page by page)read the entire book!.Do any of you have recommendations on how to proceed with this book so that I 'll rememberat least some of them by the time I am done with the book? I can see that many of the classesin java API use composition, facade etc...But other than that I don't think I 'll be able to gather anything unless I am able to rememberwhere & when to use particular pattern A, B or C...Answer: Glad to hear you got the GoF book, it's a great reference manual for patterns. Asyou've found, however, it's a bit heavy to just "read." What I recommend to people is that theypick a few of the easier, more commonly used patterns: Singleton is a no-brainer that pops upa lot. Adapter tends to get used here and there and isn't that difficult to understand. If you'redoing Swing, then definitely go learn the Observer pattern. It'll help to keep you from mixingdata and interface code. Once you've learned three or four and have used them a few times,then as you start new projects, look back to the text to see if there are opportunities in yourproject where other patterns can be used.You'll find that over time you'll use more and more of the patterns (some a lot more than others,obviously). I've often found cases where I missed a pattern during design and had "the light goon" after I'd written a bunch of code and realized I was either using a known pattern byaccident, or could have used a pattern to my advantage. When possible, I then go back andadjust the design/code to match the pattern.Keep in mind that the patterns generally don't appear as "absolute." It's expected that you mayhave variations to satisfy your application's needs.It's really helpful to others, however, if you make a quick note in your design doc/code aboutwhat pattern you were using (which helps them learn patterns too, and helps them understandwhat you were up to if they know the pattern already).