Tips to crack the Java classes

  • Abstract classes: An abstract class is defined using the keyword abstract in front of the class keyword and almost always defines at least one abstract method. An abstract class does not have to define an abstract method. If there are no abstract methods in an abstract class, then any subclasses of the abstract class can be instantiated (as long as they are not, in turn, defined using the abstract keyword).
  • Assigning a subclass type to a superclass type is perfectly legal and will run fine at runtime.
  • You cannot assign an object to a sibling object reference, even with casting.
Eg:
class Superclass { }
class Subclass1 extends Superclass { }
class Subclass2 extends Superclass { }

Superclass a = new Superclass();
 Subclass1 b = new Subclass1();
Subclass2 c = new Subclass2();

b = (Subclass1)c;

will not compile.

  • What will happen when you attempt to compile the following code?

protected class Wmid{
 private Wmid(String sName){
  System.out.println("Wmid");
 }
Wmid(){}
}
public class Ombers extends Wmid{
 public static void main(String argv[]){
 Ombers o = new Ombers();
 }
}
Answer: Give compiler error "Illegal modifier for the class Wmid; only public, abstract & final are permitted"

  • Method local inner class - Has access to all members of its enclosing class & can only access final variables of its enclosing method.
  • Anonymous class: One of the most elegant things about anonymous classes is that they allow you to define a one-shot class exactly where it is needed. In addition, anonymous classes have a succinct syntax that reduces clutter in your code. However an anonymous class cannot define any static fields, methods, or classes, except for static final constants. Interfaces cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or staticSince an anonymous class has no name, it is not possible to define a constructor for an anonymous class. If your class requires a constructor, you must use a local class instead. However, you can often use an instance initializer as a substitute for a constructor. Using an anonymous class instead of a local class is not appropriate if you need to create more than a single instance of the class each time the containing block is executed.

Comments

Popular posts from this blog

jQgrid reload with new data

Introduction to jQgrid

Rich Client based UI technologies- A Comparison of Thick Client UI tools