Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Monday, 25 April 2016

Q&A on Inner classes


Q&A on Inner classes

Q 1. What modifiers can be used with a local inner class ? 
A local inner class may be final or abstract

Q 2. Can an inner class declared inside of a method access local variables of this method ?
It's possible, if these variables are final.

Types of inner classes


1. Static member classes
Static member class is a static member of a class.
Like any other static method, a static member class has access to all static methodsof the parent, or top-level, class.

2. Member classes
Member class is also defined as a member of a class.
Unlike the static variety, the member class is instance specific and has access toany and all methods and members, even the parent's this reference.

3. Local classes
Local Classes declared within a block of code and these classes are visible only within the block.

4. Anonymous classes
These type of classes does not have any name and its like a local class.
Example

button1.addActionListener( 
   new java.awt.event.ActionListener()  {    <---- Anonymous class
       public void actionPerformed(java.awt.event.ActionEvent e) {
             // do something
       }
   } );

What are Static initializers or Static blocks ?


A static initializer block resembles a method with no name, no arguments, and no return type.
There is no need to refer to it from outside the class definition.

Syntax
static {
   // CODE
}

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.


They are typically used to initialize static fields.
Here, parameters don't make any sense, so a static initializer block doesn't have an argument list.


Example

public class StaticInitilaizer {
  public static final int A= 5;
  public static final int B; 
  // Static initializer block, 
  //  which is executed only once when the class is loaded.
  static {
        if(A == 5)
           B = 10;
        else
           B = 5;
  }

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

Using the class

System.out.println("A =" + StaticInitilaizer.A 
                    + ", B =" + StaticInitilaizer.B);


Output
A=5, B=10

Interface and Abstract class


Interface vs. Abstract class
  • Interfaces provide a form of multiple inheritance.
  • A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation.
  • Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement multiple interfaces.
  • In case of abstract class, a class may extend only one abstract class.
  • Interfaces are slower as it requires extra indirection to to find corresponding method in in the actual class.
  • Abstract classes are fast.

Similarities
  • Neither Abstract classes or Interface can be instantiated

When to use Interface or Abstract class ?
Abstract class
  • The advantage of an abstract class is that you can (partially) implement the class.
  • Use abstract Java classes when you want to provide some standard base code but want / need to force the user's of your class to complete the implementation.

Interface
  • If you have a group of classes that you want to call the same methods on; just make them implement the interface and you will be able to program to the interface, rather than one of the individual classes.
  • The advantage of an interface is that you can implement multiple interfaces, whereas you can not extend multiple abstract classes.

"From a design perspective, I tend to favor Interfaces over abstract classes.
They ensure you are not tied to a specific implementation, are simpler to work with when things get complex, and allow you to add to your application by building new classes that implement the interface."                

- Shahnawaz Khan (Blog Author)

QA. Inheritence and variable access


Scenario

public class Parent {
  int x = 5;
}

class Child extends Parent {
  int x = 6;
}

class Demo {
  public static void main(String[] args) {
     Parent p = new Child();
     System.out.println(p.x);
  }
}

Which value will get printed - parent or child one ?

Explanation
Parent class variable will be printed because instance variables always bound at compile time, here compiler already decided to use variable of parent as declared type is Parent.

Result
5

Overriding vs. Hiding


An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

Main Que. is : Can I override a static method ?
Ans. No ! You can't.

Example of Hiding
class Shaan {
  public static void method() {
    System.out.println("I am Shaan");
  }
}
class Rajesh extends Shaan {
  public static void method() {
    System.out.println("I am Rajesh");
  }
}

This compiles and runs just fine.
If you try to override a static method, the compiler doesn't actually stop you

Main que. is : Isn't it an example of a static method overriding another static method?

Ans. No ! it's an example of a static method hiding another static method.


Overriding vs. Hiding
  • When you override a method, you still get the benefits of run-time polymorphism
  • When you hide, you don't.



Sunday, 24 April 2016

Can you make a constructor final ?


No
, constructor cannot be final.

Can you call this() and super() both in a constructor ?


No
because, super() or this() must be the first statement in  a constructor.

is Method overloading possible by changing the return type of method ? Why ?


No
, as it leads to ambiguity :-S

Example
class Test { 
  int sum(int a, int b) {
     int x = a+b;
  } 
  
  double sum(int a, int b){
     double x = a+b;
  } 

  public static void main(String args[]){ 
    Test test = new Test(); 
    int result = test.sum(20,20);   // Compile time Error
               // Ambiguity : which method to call ?
               // As both have same type and sequence of argument 
  } 
}  


What is the best way of downcasting objects ?


Child class object can be assigned directly to Parent class reference variable.
When we assign parent object to child class reference, there may following use cases :

UC 1. Direct assignment - Compilation error
// Invalid way
void method(Parent parent) { 
    Child child = parent; // Compile time error
}

UC 2. Downcasting without instanceof check - May be OK or ClassCastException
// Risky way of downcasting
void method(Parent parent) { 
    Child child = (Child) parent; // OK or ClassCastException
}

UC 3. Downcasting with instanceof check - prevents ClassCastException
// Best way of downcasting
void method(Parent parent) { 
     if(parent instanceof Child){ 
          Child child = (Child) parent; // Downcast, if possible
     }
}

What is the use of constructor in Abstract class ?


We can declare constructor in Abstract class.
If we cannot make instance of abstract class why constructor allowed in abstract class?

It is used to perform some initialization (of the fields of abstract class) before the instantiation of a subclass.

A constructor in Java doesn't actually "build" the object (new keyword is used to build an object), it is used to initialize fields.

Example
abstract class Super {
      protected final String name;
      public Super(String name){
            this.name = name;
      }
      public abstract boolean printName();
}
class Child extends Super {
      public Child(String name) {
            super(name);
      }
      @Override
      public boolean printName() {
            System.out.println(this.name);
            return true;
      }
}
class AbstractConstructorTest {
      public static void main(String args[]) {
            Super supr = new Child("Child");
            supr.printName();
      }
}


Notes
  • You should define all your constructors protected because there is no point making them public as you cannot create the object.
  • You can have overloaded constructors.
  • Your subclass constructor(s) can call one constructor of the abstract class.