Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Thursday, June 23, 2016

Abstract Method and Abstract Class Example Java

Abstract Method and Abstract Class 

An abstract method does not contain any body.It contains only the method header.So we can say it is an incomplete method.An abstract class is a class that generally contains ,some abstract methods.Both the abstract  class and the abstract methods should be declared by using the key word abstract.
Since, abstract class contains incomplete methods.it is not possible to estimate the total memory required to create the object.So JVM can not create objects to an abstract class.

Abstract Method: An abstract method is a method without method body .An abstract method is written when the same method has to perform different tasks depending on the object calling it.

Abstract Class: An abstract class is a class that contains 0 or more abstract methods.

Sample Program:

/**
 * 
 */
package com.interfaceabhi;

/**
 * @author Abhinaw.Tripathi
 *
 */
abstract class MyClass
{
  abstract void calculate(double x);
}

class C extends MyClass
{

@Override
void calculate(double x)
{
System.out.println("Suare root: "+ (x*x));
}
 
}

class Cube extends MyClass
{

@Override
void calculate(double x)
{
System.out.println("Cube root: "+ (x*x*x));
}
 
}

public class AbstractClassDemo
{
/**
* @param args
*/
public static void main(String[] args)
{
C c=new  C();
c.calculate(10);

Cube cube=new Cube();
cube.calculate(20);

}


}

Result:

Square value: 100.0
Cube value: 8000.0

Can you declare a class as abstract and final also?
Ans: No,abstract class needs sub classes.final key word represents sub classes which can not be created.So, both are quite contradictory and cannot be used for the same class.


Another Sample Program:

/**
 * 
 */
package com.interfaceabhi;

/**
 * @author Abhinaw.Tripathi
 *
 */

abstract class Car
{
 int regno;
 public Car(int r)
 {
regno=r;
 }
 void opentank()
 {
System.out.println("Fill the tank");
 }
 abstract void steering(int direction,int angle);
 abstract void braking (int force);
}

class Maruti extends Car
{

public Maruti(int r) 
{ super(r);
}

@Override
void steering(int direction, int angle) 
{
System.out.println("take a turn");
System.out.println("this is ordinary steering");
}

@Override
void braking(int force)
{
System.out.println("Brakes applied");
System.out.println("These are hydraulic brakes");
}
}

class Santro extends Car
{

public Santro(int r)
{
super(r);
}

@Override
void steering(int direction, int angle)
{
System.out.println("take a turn");
System.out.println("this is power steering");
}

@Override
void braking(int force)
{
System.out.println("Brakes applied");
System.out.println("These are power brakes");
}
 
}

public class AnotherDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
  
Maruti mrt=new Maruti(1001);
Santro sntr=new Santro(5005);
Car ref;
ref=mrt;
mrt.opentank();
mrt.braking(500);
mrt.steering(1, 90);
}

}

Result:

Fill the tank
Brakes applied
These are hydraulic brakes
take a turn
this is ordinary steering

Take one more Sample Program:

/**
 * 
 */
package com.interfaceabhi;

/**
 * @author Abhinaw.Tripathi
 *
 */
abstract  class Plan
{
  protected double rate;
  
  public abstract void getRate(); 
 public void calculateBill(int units)
 {
System.out.println("Bill amount for " +units + "Units:");
System.out.println(rate*units);
 }
}

class CommercialPlan extends Plan
{

@Override
public void getRate()
{
rate=7.00;
}
}

class DomesticPlan extends Plan
{

@Override
public void getRate()
{
rate=2.0;
}
}


public class AbstractCalculateDemo
{

/**
* @param args
*/
public static void main(String[] args)
{
Plan p;
System.out.println("Commercial connection: ");
p=new CommercialPlan();
p.getRate();
p.calculateBill(250);
System.out.println("Domestic Connection : ");
p=new DomesticPlan();
p.getRate();
p.calculateBill(250);

}

}

Result: 

Commercial connection: 
Bill amount for 250Units:
1750.0
Domestic Connection : 
Bill amount for 250Units:
500.0


Monday, June 6, 2016

Java Interview Questions

1.What is difference between an Interface and Abstract Class?

Ans: An abstract class can have instance method that implements a default behavior.An Interface can only declare constants and instance methods but can not implement default behavior and all methods are implicitly abstract. A class may be declared abstract even if it has no abstract methods.

  public abstract class Test
 {
   //declare fields
  // declare non-abstract methods
     abstract void draw();
 }

An Interface has all public members and no implementation.An abstract class is a class which may have the usual flavors of class members(private,protected,etc) but has some abstract methods.

public interface Test
{
  public void function();
  public void anotherFunctin();
}

2.What is the purpose of garbage collection in java and when is it used?.

Ans: The main purpose of garbage collection is to identify and discard objects that are not required by a program(Goes out of Scope) so that their resource can be reused.So a java object is subject to garbage collect when it becomes unreachable to the program in which it is used.

3.What are pass by reference and pass by value?

Ans: Pass by reference means the passing the address of itself rather than passing the value.
         Pass by value means the passing a copy of the value to be passed.

4.What is Hash Map and Map?

Ans: Map is an interface and Hash Map is the class that implements that.
Hash Map class is roughly equivalent to Hash-table except that it is unsynchronized and permits NULL. Hash Map does not guarantee that the order of the Map will remain constant overtime. Hash Map is unsynchronized and Hash table is synchronized.

5.What is Iterator?
Ans: java collection classes provide traversal of their contents via a Iterator interface.It operates on each object in turn.

6.What is final?
Ans: A final class can not be extended that means can not be sub classed . A final method can not be overridden when its class is inherited.we can not change value of final variable ie. a constant.

7.What is Static?

Ans: Static means one per class,not one for each object no matter how many instances of a class might exist.This means that we can use them without creating  an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object and static methods are attached to a class not an-object.

A static method in a superclass can be shadowed by another static method in a subclass  as long as the original method was not declared final.

However,we can not override a static method with a non-static method.In other words we can not change a static method into an instance method in a subclass.

8.What is Overriding?
Ans: When class defines a method using the same name ,return type and arguments as a method in its superclass, the methods in the class override the method in the superclass.
When the method is invoked for an object of the class,it is the new definition of the method that is called and not the method definition from superclass.

9.What is Checked and Un-Checked Exception?
Ans: A checked exception is some subclass of exception excluding class Runtime Exception and its subclasses.Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown e.g.. IOException thrown by FileInputStream read() method.

Unchecked Exception are runtime exception and any of its subclasses.Class Error and its subclass also are unchecked.however the complier does not force client programmers either to catch the exception or declare it in a throws clause.

10.What are different types of inner classes?
Ans: 

  1. Nested top - level classes
  2. Member classes
  3. Local classes
  4. Anonymous classes

Nested top-level classes =  If you declare a class within a class and specify the static modifier,the compiler treats the class just like any other  top level class.Any class outside the declaring class access the nested class with the declaring class name acting similarly to a package .

Member Classes: Member inner classes are just like other member methods and member variables and access to the member class is restricted just like methods and variables.This means a public member class acts similarly to a nested top-level class.

Local Classes: Local classes are like local variables,specific to block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block,it would need to implement a more publicly available interface.

Anonymous Classes: Anonymous inner classes extend local inner classes one level further.as anonymous classes have no name you can not provide a constructor.

11.what is Serialization?

Ans: Serialization is a mechanism by which you can save the sate of an object by converting it to a byte stream.
The class whose instances are to be serialized should implement an interface serializeable.
The serializable interface is an empty interface,it does not contain any methods.So we do not implement any methods.
Whenever an object is to be sent over the network,objects need to be serialized.if the state of an object is to be saved ,objects need to be serialized.

12.What is Externalizable Interface?

Ans: Externalization is an interface which contains two methods read External and write External. These methods give you a control over the serialization mechanism.

13.What happens to the static fields of a class during serialization?
Ans: There are three exceptions in which serialization does not necessarily read and write to the stream.These are ...
  • Serialization ignores static fields because they are not part of any particular state.
  • Base class fields are only handled if the base class itself is serializable.
  • Transient fields.