Friday, June 24, 2011

Insight of OOP Object -- How inheritance, encapsulation and polymorphism work

                                                                                                                          

How inheritance, encapsulation and polymorphism work in C++

                                                                                                                              alexonlinux.com


Table of contents

IntroductionBACK TO TOC

Inheritance, encapsulation and polymorphism are undoubtedly the cornerstones of OOP/OOD in general and C++ in particular.
When programming C, it is very easy to remember how things work. You know that when you add an int variable to a structure it mostly grows by four bytes. You know that long is either four or eight bytes long depending on the architecture you’re working with.
Things are less obvious when moving to C++. OOP brings more abstractions to the program. As a result you are no longer sure if a+b sums two numbers or calls some overloaded operator method that concatenates contents of two files together.
In this article, I would like to give you a short insight into what’s going on behind the scenes. In particular we’ll see how the three whales of OOP work in C++.
Things that I am going to show in this article may differ from compiler to compiler. I will talk mostly about g++ (version 4.2.3). Note however, that same ideas apply everywhere.

EncapsulationBACK TO TOC

As you know, encapsulation is a principle by which same entity, the object, encapsulates data and methods that manipulate the data. You may be surprised to find out that underneath, class methods are just plain functions.

How methods workBACK TO TOC

In C++ there’s one fundamental difference between plain functions and class methods. Class methods receive one additional argument and that is the pointer to the object whose data the method is expected to manipulate. I.e. first argument to a method is pointer to this.
To speed things up, C++ developers used single CPU register (ECX/RCX on x86/x86_64) to pass pointer to this, instead of passing it via stack as if it was a regular function argument (no longer true in x86_64).
Otherwise, objects know nothing about methods that operate on them.

How overloading worksBACK TO TOC

Another thing that we have to take care of in C++ is how to distinguish between some_function() and some_class::some_function(). Or between some_class::some_function( int ) and some_class::some_function() I.e. what’s the difference between two methods with the same name that receive different number and type of arguments? What is the difference between method and function that has same name?
Obviously, out of linker, compiler and preprocessor, linker is the one that should be aware of the above difference. This is because we may have some_function() in some distant object file. Linker is the component that should find this distant function and interconnect the call to the function and the actual function. Linker uses function name as a unique identifier of the function.
To make things work, g++ and any other modern compiler, mangles the name of the method/function and makes sure that:
  1. Mangled method name includes name of the class it belongs to (if it belongs to any class).
  2. Mangled method name includes number and type of arguments method receives.
  3. Mangled method name includes namespace it belongs to.
With these three, some_class::some_function() and some_function() will have totally different mangled name. See the following code sample.
01namespace some_namespace
02{
03    class some_class
04    {
05    public:
06        some_class() { }
07        void some_method() { }
08    };
09};
10 
11class some_class
12{
13public:
14    some_class() { }
15    void some_method() { }
16};
17 
18void some_method()
19{
20    int a;
21}
g++ will turn:
  • void some_class::some_method() into _ZN10some_class11some_methodEv
  • void some_namespace::some_class::some_method() into _ZN14some_namespace10some_class11some_methodEv
  • void some_method() into _Z11some_methodv
Adding integer argument to void some_method() will turn it from _Z11some_methodv to _Z11some_methodi.

How mangling solves the problemBACK TO TOC

So when you create two methods with same name, but with different arguments, compiler turns them into two functions with different names. Later, when linker links the code together it doesn’t know that these are two methods of the same class. From linkers standpoint, these are two different functions.

Structure and size of the objectBACK TO TOC

You probably already know that C++ class and good old C structures are nearly the same thing. Perhaps the only difference is that all class members are private unless specified otherwise. On the contrary, all structure members are public.
When looking at the memory layout of the object, it is very similar to C structure.
Differences begin when you add virtual methods. Once you add virtual methods to the class, compiler will create virtual methods table for the class. Then it will place pointer to the table in the beginning of each instance of this class.
So, bear in mind that once your class has virtual methods, each object of this class will be four or eight bytes (depends on whether you have 64-bit support or not) bigger.
Actually, pointer to the virtual methods table does not have to be at the beginning of the object. It is just handy to keep it at the beginning, so g++ and most of the modern compilers do it this way.
Adding virtual methods to the class will also increase amount of RAM your program consumes and its size on your hard drive.

How inheritance and polymorphism workBACK TO TOC

Lets say we have two classes. A and B. Class B inherits from class A.
01#include <iostream>
02 
03using namespace std;
04 
05class A
06{
07public:
08    A() { a_member = 0; }
09    int a_member;
10};
11 
12class B : public A
13{
14public:
15    B() : A() { b_member = 0; };
16    int b_member;
17};
18 
19int main()
20{
21    A *a = new B;
22    a->a_member = 10;
23 
24    return 0;
25}
The interesting thing to notice here is that a actually points to instance of class B. When dereferencing a_member, we’re actually dereferencing a_member that defined in class A, but belongs to class B (via inheritance). To make this happen, compiler has to make sure that common part of both classes (a_member in our case) located at the same offset in the object.
Now what if we have some virtual methods.

How basic polymorphism worksBACK TO TOC

Let’s change our example a bit and add some virtual methods.
01#include <iostream>
02 
03using namespace std;
04 
05class A
06{
07public:
08    A() { a_member = 0; }
09    virtual int reset() { a_member = 0; }
10    void set_a_member( int a ) { a_member = a; }
11    int get_a_member() { return a_member; }
12protected:
13    int a_member;
14};
15 
16class B : public A
17{
18public:
19    B() : A() { b_member = 0; };
20    virtual int reset() { a_member = b_member = 0; }
21    virtual void some_virtual_method() { }
22    void set_b_member(int b ) { b_member = b; }
23    int get_b_member() { return b_member; }
24protected:
25    int b_member;
26};
27 
28int main()
29{
30    B *b = new B;
31    A *a = b;
32 
33    b->set_b_member( 20 );
34    b->set_a_member( 10 );
35 
36    a->reset();
37 
38    cout << b->get_a_member() << " " << b->get_b_member() <<
39        endl;
40 
41    return 0;
42}
If you compile and run this program it will obviously print “0 0″. But how, you may ask. After all we did a->reset(). Without our understanding of polymorphism we could think that we’re calling method that belongs to class A.
The reason it works is because when compiler sees code that dereferences pointer to A it expects certain internal object structure and when it dereferences pointer to B it expects different object structure. Let us take a look at both of them.
However even more important here is the structure of the virtual methods tables of both classes.
It is because of the virtual methods table structure compilers knows what virtual method to call. When it generates the code that dereferences pointer to A, it expects that first method in the virtual methods table of the object will be pointer to right reset() routine. It doesn’t really care if the pointer actually points to B object. It will call first method of the virtual methods table anyway.

How multiple inheritance worksBACK TO TOC

Multiple inheritance makes things much more complicated. The problem is that when class C inherits from both A and B, we should have both members of class A and class B in the instance of class C.
01#include <iostream>
02 
03using namespace std;
04 
05class A
06{
07public:
08    A() { a_member = 0; }
09protected:
10    int a_member;
11};
12 
13class B
14{
15public:
16    B() { b_member = 0; }
17protected:
18    int b_member;
19};
20 
21class C : public A, public B
22{
23public:
24    C() : A(), B() { c_member = 0; }
25protected:
26    int c_member;
27};
28 
29int main()
30{
31    C c;
32 
33    A *a1 = &c;
34    B *b1 = &c;
35 
36    A *a2 = reinterpret_cast<A *>( &c );
37    B *b2 = reinterpret_cast<B *>( &c );
38 
39    printf( "%p %p %p\n", &c, a1, b1 );
40    printf( "%p %p %p\n", &c, a2, b2 );
41 
42    return 0;
43}
Once we cast pointer to class C into class B, we cannot keep the value of the pointer as is because first fields in the object occupied by fields defined in class A (a_member). Therefore, when we do casting we have to do a very special kind of casting – the one that changes the actual value of the pointer.
If you compile and run above code snippet, you will see that all the values are the same except for b1, which should be 4 bytes bigger than other values.
This is what (C style casting in our case) casting does – it increments the value of the pointer to make sure that it points to the beginning of the, inherited from B, part of the object.
In case you wonder what other types of casting will do, here is a short description.

Difference between different casting typesBACK TO TOC

There are five types of casting in C++.
  1. reinterpret_cast<>()
  2. static_cast<>()
  3. dynamic_cast<>()
  4. const_cast<>()
  5. C style cast.
I guess you know already what const_cast<>() does. Also, it is only a compile time casting. C style cast is same as static_cast<>(). This leaves us with three types of casting.
  1. reinterpret_cast<>()
  2. static_cast<>()
  3. dynamic_cast<>()
From the above example we learn that reinterpret_cast<>() does nothing to the pointer value and leaves it as is.
static_cast<>() and dynamic_cast<>() both modify value of the pointer. The difference between two is that the later relies on RTTI to see if the casting is legal – it looks inside the object to see if it truly belongs to the type we’re trying to cast from. static_cast<>() on the other hand, simply increments the value of the pointer.

Polymorphism and multiple inheritanceBACK TO TOC

Things getting even more complicated when we have virtual methods in each one of the classes A, B and C that we already met. Let’s add following virtual methods to the classes.
virtual void set_a( int new_a ) { a_member = new_a; }
To class A.
virtual void set_b( int new_b ) { b_member = new_b; }
To class B and
virtual void set_c( int new_c ) { c_member = new_c; }
To class C.
You could have assumed that even in this case class C objects will have only one virtual tables methods, but this is not true. When you static_cast class C object into class B object, class B object must have its own virtual tables method. If we want to use same casting method as with regular objects (that is adding few bytes to the pointer to reach right portion of the object), then we have no choice but to place another virtual tables method in the middle of the object.
As a result, you can have many different virtual methods tables for the same class. The above diagram shows very simple case of inheritance and the truth is that it does not get more complicated than this. Take a look at the following, more complex, class hierarchy.
It may surprise you, but structure of the class X object will be quiet simple. In our previous example inheritance hierarchy had two branches. This one has three:
  1. A-C-F-X
  2. D-G-X
  3. B-E-H-X
All end up with X of course. They are a little longer than in our previous example, but there is nothing special about them. The structure of the object will be the following:
As a rule of thumb, g++ (and friends) calculates the branches that lead to the target class, class X in our case. Next it creates a virtual methods table for each branch and places all virtual methods from all classes in the branch into virtual methods table. This includes pointer to virtual methods of the class itself.
If we project this rule onto our last example. A-C-F-X branch virtual methods table will include pointers to virtual methods from classes A, C, F and X. Same with other two branches.

What if we try something even more complicatedBACK TO TOC

The thing is that you can’t. Lets say we try to create even more complicated hierarchy by changing class D from our previous example to inherit from class C.
This will immediately create ambiguous inheritance and the compiler will not hesitate to tell you that this is what happened. This is because now class X will have all members of classes A and C twice. Once it will have it via A-C-F-X branch and once via A-C-D-G-X branch. It will not tell you that there’s a problem immediately. Instead, once you will try to reference one of the members of X inherited from either A or C, g++ will tell you that it has two variations of the same member/method and that it does not know which one of them to call.
This what would be g++ output if you try to compile this file.
main.cc: In function 'int main()':
main.cc:110: error: request for member 'set_a' is ambiguous
main.cc:29: error: candidates are: virtual void A::set_a(int)
main.cc:29: error:                 virtual void A::set_a(int)
All this because I was trying to do x.set_a( 20 ); in line 110.

Few words about C++ constructorsBACK TO TOC

I guess you know what constructors are good for. In light of what we’ve seen, you may ask yourself, who is building all those virtual methods tables and who writes right pointer into the object.
Obviously compiler builds all the virtual methods tables. And constructor is the one who fills in the right virtual methods table. And this is another reason why you cannot call constructor directly – you don’t want to mess up with virtual methods tables.

Source: Click here

Wednesday, June 22, 2011

Java Interview Questions - Basic Questions

1.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.

2.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.

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

4.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 capitalized by convention) -- usually a noun Any name except the class. Method 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


5.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.

6.What are the differences between Class Methods and Instance Methods?
Class Methods Instance Methods
Class methods are methods which are declared as static. The method can be called without creating an instance of the class Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.
Class methods are methods which are declared as static. The method can be called without creating an  instance of the class. Instance methods are not declared as static.


7.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.

8.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..

9.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.
 Situation   public   protected   default   private 
 Accessible to class
 from same package? 
yes yes yes no
 Accessible to class
 from different package? 
yes  no, unless it is a subclass  no no







10.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.
11.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.

12.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.

13.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.

14.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.



15.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.
Source: Developersbook.com Click here.

OOP interview questions

(www.developersbook.com) Source: Click here.
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 Abstraction?

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

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.

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:
        To promote code reuse
        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?

          Overloaded Method     Overridden Method
    Arguments   

    Must change
      

    Must not change

    Return type
      

    Can change
      

    Can’t change except for covariant returns

    Exceptions
      

    Can change
      

    Can reduce or eliminate. Must not throw new or broader checked exceptions

    Access
      

    Can change
      

    Must not make more restrictive (can be less restrictive)

    Invocation
      

    Reference type determines which overloaded version is selected. Happens at compile time.
      

    Object type determines which method is selected. Happens at runtime.

    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.

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     Interfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.     An interface cannot provide any code at all,just the signature.
In case of abstract class, a class may extend only one abstract class.     A Class may implement several interfaces.
An abstract class can have non-abstract methods.     All methods of an Interface are abstract.
An abstract class can have instance variables.     An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.     An Interface visibility must be public (or) none.
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.     If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors .     An Interface cannot contain constructors .
Abstract classes are fast.     Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.

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.

Friday, June 17, 2011

How to create a Java XML Socket Server?

/*
* source: http://www.adobe.com 
*/ 
import java.io.*; 
import java.net.*; 
 
class SimpleServer 
{ 
    private static SimpleServer server; 
    ServerSocket socket; 
    Socket incoming; 
    BufferedReader readerIn; 
    PrintStream printOut; 
 
    public static void main(String[] args) 
    { 
        int port = 8080; 
 
        try 
        { 
            port = Integer.parseInt(args[0]); 
        } 
        catch (ArrayIndexOutOfBoundsException e) 
        { 
            // Catch exception and keep going. 
        } 
 
        server = new SimpleServer(port); 
    } 
 
    private SimpleServer(int port) 
    { 
        System.out.println(">> Starting SimpleServer"); 
        try 
        { 
            socket = new ServerSocket(port); 
            incoming = socket.accept(); 
            readerIn = new BufferedReader(new  
                            InputStreamReader(incoming.getInputStream())); 
            printOut = new PrintStream(incoming.getOutputStream()); 
            printOut.println("Enter EXIT to exit.\r"); 
            out("Enter EXIT to exit.\r"); 
            boolean done = false; 
            while (!done) 
            { 
                String str = readerIn.readLine(); 
                if (str == null) 
                { 
                    done = true; 
                } 
                else 
                { 
                    out("Echo: " + str + "\r"); 
                    if(str.trim().equals("EXIT")) 
                    { 
                        done = true; 
                    } 
                } 
                incoming.close(); 
            } 
        } 
        catch (Exception e) 
        { 
            System.out.println(e); 
        } 
    } 
 
    private void out(String str) 
    { 
        printOut.println(str); 
        System.out.println(str); 
    } 
}
// Click here to view the source.

What is MapReduce?

(wikipedia.org) MapReduce is a patented software framework introduced by Google in 2004 to support distributed computing on large data sets on clusters of computers.

MapReduce is a framework for processing huge datasets on certain kinds of distributable problems using a large number of computers (nodes), collectively referred to as a cluster (if all nodes use the same hardware) or as a grid (if the nodes use different hardware). Computational processing can occur on data stored either in a filesystem (unstructured) or within a database (structured).

"Map" step: The master node takes the input, partitions it up into smaller sub-problems, and distributes those to worker nodes. A worker node may do this again in turn, leading to a multi-level tree structure. The worker node processes that smaller problem, and passes the answer back to its master node.

"Reduce" step: The master node then takes the answers to all the sub-problems and combines them in some way to get the output – the answer to the problem it was originally trying to solve.
The advantage of MapReduce is that it allows for distributed processing of the map and reduction operations. Provided each mapping operation is independent of the others, all maps can be performed in parallel – though in practice it is limited by the data source and/or the number of CPUs near that data.
The canonical example application of MapReduce is a process to count the appearances of each different word in a set of documents:

void map(String name, String document):
  // name: document name
  // document: document contents
  for each word w in document:
    EmitIntermediate(w, "1");
 
void reduce(String word, Iterator partialCounts):
  // word: a word
  // partialCounts: a list of aggregated partial counts
  int sum = 0;
  for each pc in partialCounts:
    sum += ParseInt(pc);
  Emit(word, AsString(sum)); 
Here, each document is split into words, and each word is counted initially with a "1" value by the Map function, using the word as the result key. The framework puts together all the pairs with the same key and feeds them to the same call to Reduce, thus this function just needs to sum all of its input values to find the total appearances of that word.

Source: http://en.wikipedia.org 
Click here to view the full article on wikipedia.org