Tuesday, December 4, 2012

Understand Abstract class and Interface !!!


Abstract class and Methods



- An Abstract class can not be instantiated but they can be subclassed.

- An Abstract method is method that is declared without an implementation without braces and followed by semicolon.

Example:

public abstract class Animal{

        abstract void eat();

}

- All abstract methods must be implemented in the first concrete subclass    in the inheritance tree. 

- An abstract class can have both abstract and non abstract methods.

- When you don't want a class to be instantiated mark the class with abstract keyword.

- If a class has even one abstract method, the class must be marked abstract.


We have here AnimalObject in above image, might be all three sublcass that is Lion, cat and zebra behave totally different but other thing we find common is eat and roam. You can take advantage of similarities and declare all the animals to inherit from the same abstract object. Lion , Cat and Zebra inherit from Animal.

Example:

public abstract class Animal{
         
         abstract void eat();
         abstract void roam();
}


class Lion extends Animal{

        void eat();{
       void roam();{

}

class Cat extends Animal{

        void eat();{
       void roam();{

}


class Zebra extends Animal{

        void eat();{
       void roam();{

}


Now all this above three non abstract subclass of Animal that is Lion, Cat and Zebra must provide implementation.



Interface 



- An interface is a reference type similar to a class that can certain only constants method signature and nested types. There are no method bodies. 

- Use interface when you want different behavior different classes.

- Interface can not be implemented by class or extended by other interfaces.

- Create an interface using the "interface" keyword instead of class.


Example:

public interface mainInterface extend Interface1, Interface2, Interface3{

               void doSomething (int a, float y);
               int doSomethingElse(String s);


The public access specifier indicates that the interface that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.

An interface can extend other interfaces just as a class can extend or subclass another class. As you know that the class can only extend other class but interface can extend any number of interfaces. And it declare by  comma as shown in above example. 



Thank you for your time..............



No comments:

Post a Comment