Saturday 4 February 2017

Java Basic Questions Part 2

1) What is Runtime Polymorphism? Polymorphism is the capability of an action or method to do different things based on the object that... thumbnail 1 summary
1) What is Runtime Polymorphism?

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming.
The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time.It is also know as Dynamic method dispatch.
Let's take a look at the following example:
class Animal {
  void whoAmI() {
    System.out.println("I am a generic Animal.");
  }
}
class Dog extends Animal {
  void whoAmI() {
    System.out.println("I am a Dog.");
  }
}
class Cow extends Animal {
  void whoAmI() {
    System.out.println("I am a Cow.");
  }
}
class Snake extends Animal {
  void whoAmI() {
    System.out.println("I am a Snake.");
  }
}

class RuntimePolymorphismDemo {

  public static void main(String[] args) {
    Animal ref1 = new Animal();
    Animal ref2 = new Dog();
    Animal ref3 = new Cow();
    Animal ref4 = new Snake();
    ref1.whoAmI();
    ref2.whoAmI();
    ref3.whoAmI();
    ref4.whoAmI();
  }
}
In the example, there are four variables of type Animal (e.g., ref1, ref2, ref3, and ref4). Only ref1 refers to an instance of Animal class, all others refer to an instance of the subclasses of Animal. From the output results, you can confirm that version of a method is invoked based on the actually object's type.

In Java, a variable declared type of class A can hold a reference to an object of class A or an object belonging to any subclasses of class A. The program is able to resolve the correct method related to the subclass object at runtime. This is called the runtime polymorphism in Java. This provides the ability to override functionality already available in the class hierarchy tree. At runtime, which version of the method will be invoked is based on the type of actual object stored in that reference variable and not on the type of the reference variable.

2) What is abstraction?

Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context.
Hiding of data is known as data abstraction. In object oriented programming language this is implemented automatically while writing the code in the form of class and object.
Real Life Example of Abstraction
Abstraction shows only important things to the user and hides the internal details, for example, when we ride a car, we only know about how to ride cars but can not know about how it work? And also we do not know the internal functionality of a car.

Note: Data abstraction can be used to provide security for the data from the unauthorized methods.In Java language data abstraction can achieve using class.
class Customer
{
int account_no;
float balance_Amt;
String name;
int age;
String address;
void balance_inquiry()
{
/* to perform balance inquiry only account number
is required that means remaining properties 
are hidden for balance inquiry method */
}
void fund_Transfer()
{
/* To transfer the fund account number and 
balance is required and remaining properties 
are hidden for fund transfer method */
}

3) Difference between abstraction and encapsulation?

First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

Encapsulation is also called data hiding.

Design principles "programming for interface than implementation" is based on abstraction and "encapsulate whatever changes" is based upon Encapsulation.

4) What is 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. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Let's look at an example of an abstract class, and an abstract method.

Suppose we were modeling the behavior of animals, by creating a class hierachy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking).

Note : that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.
public abstract Animal
{
   public void eat(Food food)
   {
        // do something with food.... 
   }

   public void sleep(int hours)
   {
        try
 {
  // 1000 milliseconds * 60 seconds * 60 minutes * hours
  Thread.sleep ( 1000 * 60 * 60 * hours);
 }
 catch (InterruptedException ie) { /* ignore */ } 
   }

   public abstract void makeNoise();
}

public Dog extends Animal
{
   public void makeNoise() { System.out.println ("Bark! Bark!"); }
}

public Cow extends Animal
{
   public void makeNoise() { System.out.println ("Moo! Moo!"); }
}

Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.

5) What is Interface?

An interface is a reference type, similar to a class, which can be declared by using interface keyword. Interfaces can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Like abstract classes, Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Interface is a common way to achieve full abstraction in Java.
Notice how the Cat class must implement the inherited abstract methods in the interface. Furthermore, notice how a class can practically implement as many interfaces as needed (there is a limit of 65,535 due to JVM Limitation).
public interface NoiseMaker {
    String makeNoise(); //interface methods are public by default
}

public interface FoodEater {
    void eat(Food food);
}

public class Cat implements NoiseMaker, FoodEater { 
    @Override
    public String makeNoise() {
        return "meow";
    }

    @Override
    public void eat(Food food) {
        System.out.println("meows appreciatively");
    }
}

NoiseMaker noiseMaker = new Cat(); // Valid
FoodEater foodEater = new Cat(); // Valid
Cat cat = new Cat(); // valid

Cat invalid1 = new NoiseMaker(); // Invalid
Cat invalid2 = new FoodEater(); // Invalid

Rules : 

  • All variables declared in an interface are public static final
  • All methods declared in an interface methods are public abstract (This statement is valid only through Java 7. From Java 8, you are allowed to have methods in an interface, which need not be abstract; such methods are known as default methods)
  • Interfaces cannot be declared as final
  • If more than one interface declares a method that has identical signature, then effectively it is treated as only one method and you cannot distinguish from which interface method is implemented
  • A corresponding Interface_Name.class file would be generated for each interface, upon compilation
6) Can you declare an interface method static?

No, because methods of an interface is abstract by default, and static and abstract keywords can't be used together.

7) What is marker interface?

An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc.
Read : How to implement Cloneable interface ?

8) What is difference between abstract class and interface?

Abstract class
  • An abstract class can have method body (non-abstract methods).
  • An abstract class can have instance variables.
  • An abstract class can have constructor.
  • An abstract class can have static methods.
  • You can extends one abstract class.
Interface
  • Interface have only abstract methods.
  • An interface cannot have instance variables.
  • Interface cannot have constructor.
  • Interface cannot have static methods.
  • ou can implement multiple interfaces
9) What if same package/class import twice?

One can import the same package or same class multiple times. Neither compiler nor JVM complains about it.But the JVM will internally load the class only once no matter how many times you import the same class.

10) What do you mean by static import ?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined.
import static java.lang.System.out;
import static java.lang.Math.*;
class Demo2{
   public static void main(String args[])
   {
      //instead of Math.sqrt need to use only sqrt
      double var1= sqrt(5.0);
      //instead of Math.tan need to use only tan
      double var2= tan(30);
      //need not to use System in both the below statements
      out.println("Square of 5 is:"+var1);
      out.println("Tan of 30 is:"+var2);
   }
}

Output:
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276

11) What is nested class?

A class within another class is known as Nested class. The scope of the nested is bounded by the scope of its enclosing class.

Static Nested Class

A satic nested class is the one that has static modifier applied. Because it is static it cannot refer to non-static members of its enclosing class directly. Because of this restriction static nested class is seldom used.

Non-static Nested class
Non-static Nested class is most important type of nested class. It is also known as Inner class. It has access to all variables and methods of Outer class and may refer to them directly. But the reverse is not true, that is, Outer class cannot directly access members of Inner class.
One more important thing to notice about an Inner class is that it can be created only within the scope of Outer class. Java compiler generates an error if any code outside Outer class attempts to instantiate Inner class.
class Outer
{
 int count;
 public void display()
 {
  Inner in=new Inner();
  in.show();
 }

 class Inner
 {
  public void show()
  {
   System.out.println("Inside inner "+(++count));
  } 
 }
}

class Test
{
 public static void main(String[] args)
 {
  Outer ot=new Outer();
  Outer.Inner in= ot.new Inner();
  in.show();
 }
}
Output : Inside inner 1

12) What is anonymous class?

Anonymous inner classes of Java are called anonymous because they have no name. They are anonymous and inline. Anonymous classes are essentially inner classes and defined within some other classes. However, the way anonymous classes are written in Java code may look weird but anonymous inner classes facilitate programmers to declare and instantiate the class at the same time. Another important point to note about anonymous inner classes is that they can be used only once on the place they are coded. In other words, if you want to create only one sub-classed object of a class, then you need not to give the class a name and you can use anonymous inner class in such a case. Anonymous inner classes can be defined not just within a method, but even within an argument to a method. Anonymous inner classes cannot have explicit constructors declared because they have no name to give the constructor.
public interface Hello {

 public void sayHello();
}

Hello is an interface, let’s see how we can create an anonymous class implementation of Hello interface.
public class AnonymousExample {

 //nested anonymous class
 public static Hello hello = new Hello() {

  @Override
  public void sayHello() {
   System.out.println("Hello nested anonymous class");
  }
 };
 
 public static void main(String[] args) {
  
  //anonymous class inside method
  Hello h = new Hello() {

   @Override
   public void sayHello() {
    System.out.println("Hello anonymous class");
   }
  };
  
  h.sayHello();
  
  AnonymousExample.hello.sayHello();
 }

}

Above Hello class can be an abstract class also.

13) What is nested interface ?

An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred by the outer interface or class. It can't be accessed directly.
interface Showable{  
  void show();  
  interface Message{  
   void msg();  
  }  
}  
class TestNestedInterface1 implements Showable.Message{  
 public void msg(){System.out.println("Hello nested interface");}  
  
 public static void main(String args[]){  
  Showable.Message message=new TestNestedInterface1();//upcasting here  
  message.msg();  
 }  
}  

  • Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.
  • Nested interfaces are declared static implicitely.
14) Can an Interface have a class?

Yes you can have a class inside an interface
The class can even access the variable that's defined in the interface and the super interfaces.

No comments

Post a Comment