Thursday, August 7, 2014

Basics about Java (Class, Variables Methods, Keywords, Identfiers, Coding conventions)

About Java :

Java is a programming language and computing platform first released by Sun Microsystems in 1995.

Features Of Java

The major characteristics of Java are:
  • The programs you create are portable in a network. (See portability.) Your source program is compiled into what Java calls bytecode, which can be run anywhere in a network on a server or client that has a Java virtual machine. The Java virtual machine interprets the bytecode into code that will run on the real computer hardware. This means that individual computer platform differences such as instruction lengths can be recognized and accommodated locally just as the program is being executed. Platform-specific versions of your program are no longer needed.
  • The code is robust, here meaning that, unlike programs written in C++ and perhaps some other languages, the Java objects can contain no references to data external to themselves or other known objects. This ensures that an instruction can not contain the address of data storage in another application or in the operating system itself, either of which would cause the program and perhaps the operating system itself to terminate or "crash." The Java virtual machine makes a number of checks on each object to ensure integrity.
  • Java is object-oriented, which means that, among other characteristics, an object can take advantage of being part of a class of objects and inherit code that is common to the class. Objects are thought of as "nouns" that a user might relate to rather than the traditional procedural "verbs." A method can be thought of as one of the object's capabilities or behaviors.
  • In addition to being executed at the client rather than the server, a Java applet has other characteristics designed to make it run fast.
  • Relative to C++, Java is easier to learn. (However, it is not a language you'll pick up in an evening!)
Java was introduced by Sun Microsystems in 1995 and instantly created a new sense of the interactive possibilities of the Web. Both of the major Web browsers include a Java virtual machine. Almost all major operating system developers (IBM, Microsoft, and others) have added Java compilers as part of their product offerings.
The Java virtual machine includes an optional just-in-time compiler that dynamically compiles bytecode into executable code as an alternative to interpreting one bytecode instruction at a time. In many cases, the dynamic JIT compilation is faster than the virtual machine interpretation.

Java includes


■ Class A template that describes the kinds of state and behavior that objects of its type support.

■ Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object which is an instance of that class. That object will have its own state, and access to all of the behaviors defined by its class.

■ State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state. 

■ Behavior (methods) When a programmer creates a class, she creates methods for that class. Methods are where the class' logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.


Identifiers

All the Java components we just talked about—classes, variables, and methods— need names. In Java these names are called identifiers, and, as you might expect, there are rules for what constitutes a legal Java identifier. 

The three aspects of Java identifiers that we cover here are:

■ Legal Identifiers The rules the compiler uses to determine whether a  name is legal.
    Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).  

Here are some of the rules you do need to know:

  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.  
  • You can't use a Java keyword as an identifier.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.

Examples of legal and illegal identifiers follow, first some legal identifiers:

  • int identifier1;
  • char _name;
  • int  _________2_w;
  • float $currency;
  • int this_is_a_very_big_identifier;

The following are illegal:

  • int :b;
  • int -d;
  • int e#;
  • int .f;
  • int 7g;


■ Sun's Java Code Conventions Sun's recommendations for naming classes, variables, and methods. Sun has created a set of coding standards for Java, and published those standards in a document cleverly titled "Java Code Conventions," which you can find at java.sun.com. It's a great document, short and easy to read and we recommend it highly.

Here are the naming standards that Sun recommends:


Classes and interfaces The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "camelCase"). For classes, the names should typically be nouns. For example:
  • Dog
  • Account
  • PrintWriter
  • For interfaces, the names should typically be adjectives like
    • Runnable
    • Serializable

Methods The first letter should be lowercase, and then normal camelCase rules should be used. In addition, the names should typically be verb-noun pairs. For example:
  • getBalance
  • doCalculation
  • setCustomerName


Variables Like methods, the camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us. Some examples:
  • buttonWidth
  • accountBalance
  • myString

Constants Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators:

  • MIN_HEIGHT

JavaBeans Naming Standards The naming requirements of the JavaBeans specification.
By using naming rules, the JavaBeans spec helps guarantee that tools can recognize and use components built by different developers.

First, JavaBeans are Java classes that have properties. For our purposes, think of 
properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

JavaBean Property Naming Rules

If the property is not a boolean, the getter method's prefix must be get. For example, getSize()is a valid JavaBeans getter name for a property named "size".
■ If the property is a boolean, the getter method's prefix is either get or is. For example, getStopped() or isStopped() are both valid JavaBeans names for a boolean property.
■ The setter method's prefix must be set. For example, setSize() is the valid JavaBean name for a property named size. 
■ To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then append it to the appropriate prefix (get, is, or set). 
■ Setter method signatures must be marked public, with a void return type and an argument that represents the property type. 
■ Getter method signatures must be marked public, take no arguments, and have a return type that matches the argument type of the setter method for that property.

JavaBean Listener Naming Rules
■ Listener method names used to "register" a listener with an event source must use the prefix add, followed by the listener type. For example, addActionListener() is a valid name for a method that an event source will have to allow others to register for Action events.
■ Listener method names used to remove ("unregister") a listener must use the prefix remove, followed by the listener type (using the same rules as the registration add method).
■ The type of listener to be added or removed must be passed as the argument to the method.
■ Listener method names must end with the word "Listener". 

Examples of valid JavaBean method signatures are

  • public void setMyValue(int v)
  • public int getMyValue()
  • public boolean isMyStatus()
  • public void addMyListener(MyListener m)
  • public void removeMyListener(MyListener m)

Examples of invalid JavaBean method signatures are

  • void setCustomerName(String s) // must be public
  • public void modifyMyValue(int v) // can't use 'modify'
  • public void addXListener(MyListener m) // listener type mismatch



 Keywords


abstract
const
finally
int
public
this
assert
boolean
continue
float
interface
return
throw
enum
break
default
for
long
short
throws

byte
do
goto
native
static
transient

case
double
if
new
strictfp
try

catch
else
implements
package
super
void

char
extends
import
private
switch
volatile

class
final
instanceof
protected
synchronized
while


Monday, January 6, 2014

Core Java Questions



CORE JAVA QUESTIONS

OOPS Interview Questions

1.What are the principle concepts of OOPS?
There are four principle concepts upon which object oriented design and programming rest. They are:
•    Abstraction
•    Polymorphism
•    Inheritance
•    Encapsulation
(i.e. easily remembered as A-PIE).

2.What is an Abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations.

Abstraction in Object Oriented Programming helps to hide the irrelevant details of an object. Abstraction is separating the functions and properties that logically can be separated to a separate entity which the main type depends on.

So here we just using jSp  Tags, but we are not aware of these tag implementations, those are hidden by Java People.
Interface an abstract class

3. What is Encapsulation?

Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

Encapsulation in Java or object oriented programming language is a concept which enforce protecting variables, functions from outside of class, in order to better manage that piece of code and having least impact or no impact on other parts of program duec to change in protected code. Encapsulation in Java is visible at different places and Java language itself provide many construct to encapsulate members. You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifier like protected or public.

-Private or protected members
- using accessors and mutators  (setters and getters)

The idea of private class members (attributes, fields) is to access them directly inside the declaring class (not instance!) only. All other classes will have to use other accessors, for example getter and setter methods. So the way how the AdressBookEntry stores the name, address, telNo and email values, is perfectly hidden inside the class.


4.What is the difference between abstraction and encapsulation?

Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
•    Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

5.What is Inheritance?

Inheritance is the process by which objects of one class acquire the properties of objects of another class.
•    A class that is inherited is called a superclass.
•    The class that does the inheriting is called a subclass.
•    Inheritance is done by using the keyword extends.
•    The two most common reasons to use inheritance are:
o  To promote code reuse
o  To use polymorphism

6.What is Polymorphism?

Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

7.How does Java implement polymorphism?

(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name.

•    In some cases, multiple methods have the same name, but different formal argument lists
(overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

8.Explain the different forms of Polymorphism.

There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:

•    Method overloading
•    Method overriding through inheritance
•    Method overriding through the Java interface

9.What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

10.What is Dynamic Binding?

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

11.What is method overloading?

Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement
methods that support the same semantic operation but differ by argument number or type.
Note:
•    Overloaded methods MUST change the argument list
•    Overloaded methods CAN change the return type
•    Overloaded methods CAN change the access modifier
•    Overloaded methods CAN declare new or broader checked exceptions
•    A method can be overloaded in the same class or in a subclass

12.What is method overriding?

Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:

The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
•    You cannot override a method marked final
•    You cannot override a method marked static

13.What are the differences between method overloading and method overriding?

Arguments

Return type

Exceptions

Access

Invocation


14.Can overloaded methods be override too?

Yes derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.,

15.Is it possible to override the main method?
NO, because main is a static method. A static method can't be overridden in Java.

16.How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.

// From subclass super.overriddenMethod();
17.What is super?

super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides
one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:

•    You can only go back one level.
In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.

18.How do you prevent a method from being overridden?

To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.

public final void exampleMethod() {
//  Method statements
}

19.What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must have.

Note:

•    You can’t mark an interface as final.
•    Interface variables must be static.
•    An Interface cannot extend anything but another interfaces.

20.Can we instantiate an interface?

You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.

21.Can we create an object for an interface?

Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.

public interface MyInterface {

    public String hello = "Hello";

    public void sayHello();
}

22.Do interfaces have member variables?

Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.

23.What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

24.What is a marker interface?

Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

25.What is an abstract class?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:

•    If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
•    You can’t mark a class as both abstract and final.

26.Can we instantiate an abstract class?

An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

27.What are the differences between Interface and Abstract class?

Abstract Class


  • An abstract class can provide complete, default code and/or just the details that have to be overridden.
  • In case of abstract class, a class may extend only one abstract class.
  • An abstract class can have non-abstract methods.
  • An abstract class can have instance variables.
  • An abstract class can have any visibility: public, private, protected.
  • If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
  • An abstract class can contain constructors .
  • Abstract classes are fast.


28.When should I use abstract classes and when should I use interfaces?

Use Interfaces when…

•    You see that something in your design will change frequently.
•    If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.

Use Abstract Class when…

If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.

29.When you declare a method as abstract, can other nonabstract methods access it?

Yes, other nonabstract methods can access a method that you declare as abstract.

30.Can there be an abstract class with no abstract methods in it?

Yes, there can be an abstract class without abstract methods.

31.What is Constructor?

•    A constructor is a special method whose task is to initialize the object of its class.
•    It is special because its name is the same as the class name.
•    They do not have return types, not even void and therefore they cannot return values.
•    They cannot be inherited, though a derived class can call the base class constructor.
•    Constructor is invoked whenever an object of its associated class is created.

32.How does the Java default constructor be provided?

If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.

33.Can constructor be inherited?

No, constructor cannot be inherited, though a derived class can call the base class constructor.

34.What are the differences between Contructors and Methods?

Constructors                                              Methods

Purpose               Create an instance of a class                    Group Java statements


Modifiers            Cannot be abstract, final, native, static, or synchronized

Can be abstract, final, native, static, or synchronized


Return Type       No return type, not even void                  void or a valid return type

Name                   Same name as the class (first letter is      Any name except the class. Method

capitalized by convention) -- usually a noun

names begin with a lowercase letter by convention -- usually the name of an action



this                       Refers to another constructor in the same class. If used, it must be the first line of the constructor

Refers to an instance of the owning class. Cannot be used by static methods.



super                    Calls the constructor of the parent class. If used, must be the first line of the constructor

Calls an overridden method in the parent class


Inheritance         Constructors are not inherited                 Methods are inherited


35.How are this() and super() used with constructors?

Constructors use this to refer to another constructor in the same class with a different parameter list.
•    Constructors use super to invoke the superclass's constructor. If a constructor uses super,
it must use it in the first line; otherwise, the compiler will complain.

36.What are the differences between Class Methods and Instance Methods?

Class Methods

Class methods are methods which are declared as static. The method can be called without creating an instance of the class

Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.

Class methods are methods which are declared as static. The method can be called without creating an instance of the class.


37.What are Access Specifiers?

One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..

39.What are Access Specifiers available in Java?

Java offers four access specifiers, listed below in decreasing accessibility:

•    Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
protected


yes


no, unless it is a subclass
private


no


no
public


yes


yes
Situation

Accessible to class from same package?

Accessible to class
from different package?
default


yes


no







40.What is final modifier?

The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.

•    final Classes- A final class cannot have subclasses.
•    final Variables- A final variable cannot be changed once it is initialized.
•    final Methods- A final method cannot be overridden by subclasses.

41.What are the uses of final method?

There are two reasons for marking a method as final:

•    Disallowing subclasses to change the meaning of the method.
     Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

42.What is static block?

Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.

43.What are static variables?

Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.

static type  varIdentifier;

where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.

44.What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

45.What are static methods?

Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:

•    A static method can only call other static methods.
•    A static method must only access static data.
•    A static method cannot reference to the current object using keywords super or this.




46. Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?
The very first class is especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.

CLASS LOADER reloadable? Explanation
Bootstrap
(primordial) No Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar) rt.jarcontains all of the compiled class files for the base Java Runtime environment.
Extensions No Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
System No Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line
options)


Q.  What do you need to do to run a class with a main() method in a package?

 Say,  you  have  a  class  named  “Pet”  in  a  project  folder  “c:\myProject”  and  package  named com.xyz.client, will you be able to compile and run it as it is?

package com.xyz.client;

public class Pet {
public static void main(String[] args) { System.out.println("I am found in the classpath");
}
}

To run   c:\myProject> java com.xyz.client.Pet

The answer is no and you will get the following exception: “Exception in thread "main" java.lang.- NoClassDefFoundError: com/xyz/client/Pet”. You need to set the classpath. How can you do that? One of the following ways:

1. Set the operating system CLASSPATH environment variable to have the project folder “c:\myProject”. [Shown in the above diagram as the System –classpath class loader]
2.    Set the operating system CLASSPATH environment variable to have a jar file “c:/myProject/client.jar”, which
has the Pet.class file in it. [Shown in the above diagram as the System –classpath class loader].
3.    Run it with –cp or –classpath option as shown below:

c:\>java –cp c:/myProject com.xyz.client.Pet
OR
c:\>java -classpath c:/myProject/client.jar com.xyz.client.Pet

Q. Explain static vs. dynamic class loading?


Q. What are “static initializers” or “static blocks with no function names”? When a class is loaded, all blocks that are  declared static and don’t have function name (i.e. static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields. CO

public class StaticInitializer {
public static final int A = 5;
public static final int B; //note that it is not   public static final int B = null;
//note that since B is final, it can be initialized only once.

//Static initializer block, which is executed only once when the class is loaded.

static {
if(A == 5) B = 10;
else
B = 5;
}

public StaticInitializer(){} //constructor is called only after static initializer block
}

The following code gives an Output of A=5, B=10.

public class Test {
System.out.println("A =" + StaticInitializer.A + ", B =" + StaticInitializer.B);
}

47. How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between composition and aggregation?
  The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for

Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses
extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a
Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.















Q. Which one to favor, composition or inheritance? The guide is that inheritance should be only used when
subclass ‘is a’ superclass.

Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse. Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the superclass is modified.

Do not  use inheritance just to get polymorphism. If there is no ‘is a’  relationship and all you  want is polymorphism then use interface inheritance with composition, which gives you code reuse (Refer Q10 in Java section for interface inheritance).

What is the difference between aggregation and composition?











47 What is design by contract? Explain the assertion construct?
A 11: Design by contract specifies the obligation(duty) of a calling-method and called-method to each other. Design by contract is a valuable technique, which should be used to build well-defined interfaces.   The strength of this programming methodology is that it gets the programmer to think clearly about what a function does, what pre and post conditions it must adhere to and also it provides documentation for the caller. Java uses the assert statement to implement pre- and post-conditions. Java’s exceptions handling also support design by contract especially checked exceptions (Refer Q39 in Java section for checked exceptions). In design by contract in addition to specifying programming code to carrying out intended operations of a method the programmer also specifies:


1. Preconditions – This is the part of the contract the calling-method must agree to. Preconditions specify the conditions that must be true before a called method can execute. Preconditions involve the system state and the arguments passed into the method at the time of its invocation. If a precondition fails then there is a bug in the calling-method or calling software component.

On public methods On non-public methods
Preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. You should not use assertion to check the parameters of the public methods but can use for the non-public methods. Assert is inappropriate because the method guarantees that it will always enforce the argument checks. It  must check its  arguments whether or  not assertions are enabled. Further, assert construct does not throw an exception of a specified type. It can throw only an AssertionError.

public void setRate(int rate) {
if(rate <= 0 || rate > MAX_RATE){
throw new IllegalArgumentException(“Invalid rate  ” + rate);
}
setCalculatedRate(rate);
} You can use assertion to check the parameters of the non-public methods.

private void setCalculatedRate(int rate) {
assert (rate > 0 && rate < MAX_RATE) : rate;
//calculate the rate and set it.
}

Assertions can be disabled, so programs must not assume that assert construct will be always executed:

//Wrong:
//if assertion is disabled, “pilotJob” never gets removed
assert jobsAd.remove(pilotJob);

//Correct:
boolean pilotJobRemoved = jobsAd.remove(pilotJob);
assert pilotJobRemoved;

2. Postconditions – This is the part of the contract the called-method agrees to. What must be true after a method completes successfully.   Postconditions can be used  with assertions in both public  and non-public methods. The postconditions involve the old system state, the new system state, the method arguments and the method’s return value. If a postcondition fails then there is a bug in the called-method or called software component.

public double calcRate(int rate) {
if(rate <= 0 || rate > MAX_RATE){
throw new IllegalArgumentException(“Invalid rate !!! ”);
}

//logic to calculate the rate and set it goes here

assert this.evaluate(result) < 0 : this; //message sent to AssertionError on failure return result;
}

3. Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method completes. If an invariant fails then there could be a bug in either calling-method or called-method. There is no particular mechanism for checking invariants but it is convenient to combine all the expressions required for checking invariants into a single internal method that can be called by assertions. For example if you have a class, which deals with negative integers then you define the isNegative() convenient internal method:

class NegativeInteger {
Integer value = new Integer (-1); //invariant

//constructor
public NegativeInteger(Integer int) {
//constructor logic goes here
assert isNegative();
}

// rest of the public and non-public methods goes here. public methods should call
// assert isNegative(); prior to its return

// convenient internal method for checking invariants.
// Returns true if the integer value is negative

private boolean isNegative(){
return value.intValue() < 0 ;
}
}


The  isNegative() method should be true  before  and  after any  method completes,  each  public  method  and constructor should contain the following assert statement immediately prior to its return.

assert isNegative();

Explain the assertion construct? The assertion statements have two forms as shown below:

assert Expression1;
assert Expression1 : Expression2;

Where:
Expression1  is a boolean expression. If the Expression1 evaluates to false, it throws an AssertionError without any detailed message.
       Expression2  if the Expression1 evaluates to false throws an AssertionError with using the value of the Expression2 as
the error’s detailed message.

Note:   If you are using assertions (available from JDK1.4 onwards), you should supply the JVM argument to enable it by package name or class name.

java -ea[:packagename...|:classname] or java -enableassertions[:packagename...|:classname]
java –ea:Account

Q. When to use an abstract class?: In case where you want to use implementation inheritance then it is usually  provided by an abstract  base class.  Abstract  classes are  excellent  candidates inside of  application frameworks. Abstract classes let you define some default behavior and force subclasses to provide any specific behavior. Care should be taken not to overuse implementation inheritance as discussed in Q10 in Java section.

Q. When to use an interface?: For polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract.  CO  Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition. For example: The Spring framework’s dependency injection promotes code to an interface principle. Another justification for using interfaces is that they solve the ‘diamond problem’ of traditional multiple inheritance as shown in the figure. Java does not support multiple inheritance. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by this ‘diamond problem’.



48 What is the main difference between pass-by-reference and pass-by-value?
Other languages use pass-by-reference or pass-by-pointer. But in Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (i.e. copy-by-value) works.
If your method call involves inter-process (e.g. between two JVMs) communication, then the reference of the calling method has a different address space to the called method sitting in a separate process (i.e. separate JVM). Hence inter-process communication involves calling method passing objects as arguments to called method
by-value in a serialized form, which can adversely affect performance due to marshaling and unmarshaling cost.




Sunday, January 20, 2013

Java Inner Classes



Inner Classes: Classes within another classes are known as Nested or Inner Classes.

Difference Between Inner Classes and Normal Classes:
Normal class:  does not have a class within another class and is a top level class and a member of package.


Inner Classes: does have a class within another class and is a member of  enclosing/outer class.

Additional Information: 

  • Inner Classes were introduced in Java 1.1.
  • They may be defined as public, protected, private, or with package access.
  • The outer class can freely instantiate inner class objects within its code; they are automatically associated with the outer class instance that created them.
  • Code in some other class can instantiate an inner class object associated with a specific instance of the outer class if the inner class definition is public (and its enclosing/outer class is public as well)
  • If the inner class is static, then it can be instantiated without an outer class instance, otherwise, the inner class object must be attached to an instance of the outer class.
  • Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is).
  • Outer class code has free access to all elements in any of its inner classes, no matter what their access term.
  • No inner class objects are automatically instantiated with an outer class object.Outer class code may instantiate any number of inner class objects - none, one, or many.
  • An inner class compiles to its own class file, separate from that of the outer class (the name of the file will be OuterClassName$InnerClassName.class, although within your code the name of the class will be OuterClassName.InnerClassName); you cannot use the dollar sign version of the name in your code.
  • An inner class occupies its own memory block, separate from the outer class memory block.
  • An inner class may extend one class, which might be unrelated to the class the outer class extends.
  • An inner class can implement one of more interfaces, and, if treated as an instance of one of its interfaces, external code may have no knowledge that the object actually comes from an inner class.
  • Inner classes are best used in the event handling mechanism and to implement the helper classes. The advantage of using inner class for event handling mechanism is that the use of if/else to select the component to be handled can be avoided. If inner classes are used each component gets its own event handler and each event handler implicitly knows the component it is working
 for. e.g.
Button btn1 = new Button("Submit"); 
Btn.addActionListener(new ActionListener()
{/br>
Public void actionPerformed(ActionEvent ae)
{ submitClicked(); }
} );



Inner Class Syntax:
[modifiers] class OuterClassName {
    code
    [modifiers] class InnerClassName [extends BaseClassToInner] [SomeInterface[, MoreInterfaces, ...]] {
        fields and methods
    }


Inner Class Sample: 

public class OuterExample {
  private int num1;
  OuterExample(int num1, int num2) {
    this.num1 = num1;
    new MyInner(num2).privateDisplay();
  }// end of constructor
  public class InnerExample {
    private int num2;
    InnerExample(int num2) {
      this.num2 = num2;
    } // end of constructor
    private void privateDisplay() {
      System.out.println("privateDisplay num1 = " + num1 + " and num2 = " + num2);
    } // end of privateDisplay()
    public void publicDisplay() {
      System.out.println("publicDisplay num1 =  " + num1 + " and num2 = " + num2);
    } // end of publicDisplay()
  } // end of InnerClass
} // end of OuterClass

OuterExample has one property, x; the inner class MyInner has one property, y.
The OuterExample constructor accepts two parameters; the first is used to populate x.
It creates one InnerExample object, whose y property is populated with the second parameter.
Note that the inner class has free access to the private outer class x element.
The outer class has free access to the private inner class privateDisplay() method.
The connection between the two classes is handled automatically.





Class Files Generation for Inner Classes

As we mentioned earlier each class can have more than one inner classes. Once the main class is compiled which has several inner classes, the compiler generates separate class files for each of the inner class. Have a look at below example.

// Main class
public class Main {

    // Inner class Test1
    class Test1 {
    }

    // Inner class Test2
    class Test2 {
    }


    public static void main(String [] args) {
     
        // Anonymous inner class 1
        new Object() {
        };

        // Anonymous inner class 2
        new Object() {
        };

        System.out.println("Hello World");
    }
}

Here we have a Main class which has four inner classes. Test1, Test2, Anonymous inner class 1 and Anonymous inner class 2. Once we compile this class using javac command, the compiler will generates following class files.
Main.class
Main$Test1.class
Main$Test2.class
Main$1.class
Main$2.class




Advantages:

  1. Increases level of encapsulation : They can be hidden from the other classes in the same package and still have the access to all the members (private also) of the enclosing class. So the outer class members which are going to be used by the inner class can be made private and the inner class members can be hidden from the classes in the same package. This increases the level of encapsulation.
  2. Inner classes allow us to further organize our package structure through the use of namespaces. Instead of dumping everything in a flat package, classes can be further nested within classes. Explicitly, without inner classes, we were limited to the following hierarchy structure:
                   package1
                                  class 1
                                 class 2
                                 ...
                                class n
                                ...
                     package n


With inner classes we can do the following:

                   package 1
                                 class 1
                                 class 2
                                         class 1
                                         class 2
                                         ...
                                        class n
                                ...
                               class n
                   ...
                  package n

Used carefully, inner classes can provide a structural hierarchy that more naturally fits your classes.

3. The callback : Provide a specialized form of callback, with which a class may pass very limited access to some of its internal components. Note that:
The collections classes provide an iterator, a class that implements the Iterator interface to loop through the elements in the collection using hasNext and next methods.Given that the internal structure of the collection may be complex, implementing the iterator as an inner class enables it to navigate the structure, while not exposing any other aspects of the collection to the outside world.
4. Having the ability to define nested classes will help grouping the related functionality together, imagine the case in which a certain class is being used only once from within another class, then there is no obvious need to add a clutter to the enclosing package by defining a top-level-class that will merely be used by only one another class. Thus, having that functionality contained within a a nested class increase readability and reduce clutter.


Disadvantages :

  1. From a maintenance point of view, inexperienced Java developers may find the inner class difficult to understand. 
  2. The use of inner classes will also increase the total number of classes in your code. JVM may have to perform some routine tasks for these extra classes created which may result slower performance if the application is using more number of inner classes.  
  3.  Inner classes get limited support of ide/tools as compared to the top level classes, so working with the inner classes is sometimes annoying for the developer.




Types Of Inner Classes: There are four types of inner classes: 

  1. Static inner classes: 

    1. Static members of the outer class are visible to the static inner class, what ever their access level be.
    2. Non-static members of the outer class are not available, because there is not instance of the outer class.
    3. An inner class may not have static members unless the inner class is itself marked as static.
    4. Sometimes static nested class are not reffered to as inner class at all, as they don’t require outer classes instance.
    5. A static inner class is just like any other inner class, but it dose not have the reference to its outer class object that generated it

Static Inner Class Sample: 


public class OuterClass{
    static int i =10;    private int private_member_variable = 100;
    public static class StaticInnerClass    {       
static int j =1000; 
       public void printPrivateVariables()        {            OuterClass outerClass = new OuterClass();            System.out.println(outerClass.private_member_variable);

            System.out.println(outerClass.i);

   System.out.println(j);

        }    }
    public static void main(String args[])    {        StaticInnerClass staticInnerClass = new StaticInnerClass();        staticInnerClass.printPrivateVariables();    }}

Output: 

100

10
1000

  1. Non Static Inner classes

    1. Member Classes: 

      1. Classes declared outside a function (hence a "member") and not declared "static".
      2. The member class can be declared as public, private, protected, final and abstract. .
      3. Cannot include any static members within the inner class.
      4. These are the most widely used type of nested classes, the following code excerpt shows how to define a an inner class within a normal top-level-class, how easily the private members of the enclosing class can be accessed by the nested class and how to obtain an instance of the inner class from within the enclosing class:

Member Class Sample: 

public class OuterClass
{
   static int i =10;
private int private_member_variable = 100;
    public class MemberInnerClass
    {
//static int j =1000; //does not include static member in the inner class
        public void printPrivateVariables()
        {
        //OuterClass outerClass = new OuterClass();
            System.out.println(private_member_variable);
   System.out.println(i);  //call outer class static members
  
        }
    }
    public static void main(String args[])
    {
        //StaticInnerClass staticInnerClass = new StaticInnerClass(); // cannot directly call the class
OuterClass outerClass = new OuterClass(); // called using outer class instance
OuterClass.MemberInnerClass memberInnerClass = outerClass.new MemberInnerClass(); 
   memberInnerClass.printPrivateVariables();
    }
}

Call From outside Class:


public class TestClass
{
    public static void main(String args[])
    {
        OuterClass outerClass = new OuterClass();
        OuterClass.MemberInnerClass memberInnerClass = outerClass.new MemberInnerClass(); 
        memberInnerClass.printPrivateVariables();
    }
}




2. Local Classes:

  • Local classes are never declared with an access specifier (that is, public or private). Their scope is always restricted to the block in which they are declared.
  • Local classes have a great advantage: they are completely hidden from the outside world.
  • They can not only access the instance variables but local variables of the method (in which they are defined) as well, but the local variable has to be declared final.
  • Do not need to instantiate the local class can instantiate the outer class and call the method of the outer class.
Local Class Syntax: 

<access-specifier> class <OuterClassName> {
    code...
    <access-specifier> <return-type> <MethodName>(<arguments>){
        class <LocalInnerClassName>{
            code...
        }
        code...
    }
    code...
}



Local Class Sample: 

public class LocalInnerClass {
int i = 9;
static int j = 10;
public void method1() {
final int k = 6; 
class MethodLocal { 
void doMethodLocal() { 
System.out.println(k + i); 
System.out.println(i);
System.out.println(j); 
}//end of inner method 
} // end off local class
MethodLocal methodLocal = new MethodLocal(); // should be declared after the local class is defined
methodLocal.doMethodLocal();
} // end of outer class method
 public static void main(String args[])
    {
        //StaticInnerClass staticInnerClass = new StaticInnerClass(); // cannot directly call the class
LocalInnerClass localInnerClass = new LocalInnerClass(); // called using outer class instance
//LocalInnerClass.MethodLocal memberInnerClass = outerClass.new MethodLocal(); // do not need to instantiate the local class call using the instance of the outerclass
   localInnerClass.method1();
    } // end of main method

} // end of class




3. Anonymous Classes:

When using local inner classes, you can often go a step further. If you want to make only a single object of this class, you don’t even need to give the class a name.

Such a class is called an anonymous inner class. Usually the inner class extend some interface or extend other class.

Anonymous Classes Syntax

new SuperType(construction parameters) {
    inner class methods and data
}


  • Here, SuperType can be an interface, such as ActionListener; then, the inner class implements that interface. Or SuperType can be a class; then, the inner class extends that class.
  • An anonymous inner class cannot have constructors because the name of a constructor must be the same as the name of a class, and the class has no name. Instead, the construction parameters are given to the superclass constructor. In particular, whenever an inner class implements an interface, it cannot have any construction parameters. Nevertheless, you must supply a set of parentheses as in 
             new InterfaceType () { methods and data }

  • It is recommended to refrain from using them as many programmers find too many anonymous classes hard to read.
  • Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
  • Also, like local classes, anonymous classes cannot be public, private, protected, or static



Anonymous Classes Sample

class hasAnonymous{ 
               superClass anon = new superClass(){ 
                       void doSomething() { 
                               System.out.println(“Doing something in the Anonymous class”); 
                     } 
            }; 




Check your knowledge about Inner Classes