Showing posts with label Inheritance in Java. Show all posts
Showing posts with label Inheritance in Java. Show all posts

Question Related to Abstract Class

Q1: Must abstract classes contain at least one abstract method?
A: No, abstract classes are not required to have any abstract methods, they can simply be marked abstract for general design reasons. An abstract class may contain a full set of functional, integrated methods but have no practical use in its basic form, for example. In other words, they may require extension with additional methods to fulfil a range of different purposes. If the purpose is not specified by abstract method signatures, the range of potential applications for subclasses can be very broad.

Q2: How can an abstract method be inherited?
A: A subclass inherits all non-private fields and methods of its superclass whether the methods are abstract or have concrete implementations. If a subclass does not implement an abstract method, the subclass must be declared abstract itself. That means that an abstract method can be inherited through numerous abstract classes without any concrete implementation.
A common use of abstract methods is the template design pattern, where the common behaviour of a class hierarchy is defined in a set of concrete methods in an abstract superclass. Those core methods include calls to abstract template methods which must be implemented in concrete subclasses. This makes it relatively easy to implement subclasses and produce type-specific behaviour in each.
 
Q3: Why can't an abstract method be declared private?
A: The private and abstract method modifiers do not make sense in combination and the compiler should normally fail with a warning in this case. An abstract method must be overridden by any subclass, but subclasses do not have access to their superclass' private fields, so a private abstract method could never be fulfilled.

Q4: Why can't abstract methods be declared static?
A: The rule against static abstract methods is fundamentally a Java language design decision, which is not explained in the Java Language Specification. The abstract inheritance and implementation scheme is concerned with forming a structured collaboration of classes with deferred implementation of its abstract instance methods. This scheme can be verified at compile time to ensure it is safe at runtime.
Static methods must be concrete because they are attached to a specific host class and must be available to execute in a static context, when no object instance exists. It is not possible to assign an implementation to a static method at runtime, there is no mechanism to do that in Java.
It is also worth noting that static methods cannot be overridden by a subclass in Java. Static methods with the same signature effectively hide the superclass method. The concept of implementing a static method in a subclass would fail for the same reason, the concrete implementation would be attached to the “wrong” host.

Abstract Class In Java


Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.
To declare that your class is an abstract class, use the keyword abstract before the class keyword in your class declaration:

abstract class Number {
. . .
}

If you attempt to instantiate an abstract class, the compiler displays an error similar to the following and refuses to compile your program:
AbstractTest.java:6: class AbstractTest is an abstract class.
It can't be instantiated.
new AbstractTest();
^
1 error

Points of abstract class :
1    Abstract class contains abstract methods.
2    Program can't instantiate an abstract class.
3    Abstract classes contain mixture of non-abstract and abstract methods.
4    If any class contains abstract methods then it must implements all the abstract methods of the abstract class.


Here is a simple example of a class with an abstract method, followed by a class which implements that method:
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete method called callmetoo( ). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.
 

Advantage of Abstract Classes

The advantage of using an abstract class is that you can group several related classes together as siblings. Grouping classes together is important in keeping a program organized and understandable. 

An Abstract class is a way to organize inheritance, sometimes it makes no since to implement every method in a class (i.e. a predator class), it may implement some to pass to its children but some methods cannot be implemented without knowing what the class will do (i.e. eat() in a Tiger class). Therefore, abstract classes are templates for future specific classes.

Disadvantage of Abstract Classes

A disadvantage is that abstract classes cannot be instantiated, but most of the time it is logical not to create a object of an abstract class.
 

Difference Between Interface and Abstract Class

1) An Interface should contain only definitions but no implementation. where as an abstract class can contain abstract and non-abstract methods. 
2) Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
3) Abstract class contains the method defination of the some methods. but Interface contains only method declaration, no defination provided.
4) Interface must always have by default public and abstract methods.while abstract class can have non abstract methods
5) Abstract classes must be given by keyword abstract,where as in interface class with key word interface
6) By default what ever variables we declare in interface are public static final,where as in abstract class they can be default and instance variables also .
7) Abstract classes have constructors whereas interface do not have constructors.
8) Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
9) An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
10) In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
11) Abstract classes are used only when there is a “is-a” type of relationship between the classes. Whereas Interfaces can be implemented by classes that are not related to one another.
12) You cannot extend more than one abstract class. While You can implement more than one interface. 

Is interface is Final in Java?


Is interface is Final in Java? 

Interfaces are 100% abstract and the only way to create an instance of an interface is to instantiate a class that implements it. Allowing interfaces to be final is completely pointless.
A final interface is one that cannot be extended by other interfaces .but it is senseless that we cannot implements or extends the inheritance.because to declare an interface means to implements its methods which we can't do if we mark interface as final.
So interface is never final in  java.
Lets take an example
 final interface Test{
}
Trying to declare an interface as final in Java results in a compilation error. This is a language design decision - Java interfaces are meant to be extendable.
final interface Test {}
$ javac Test.java
Test.java:1: illegal combination of modifiers: interface and final
final interface Test {}
 ^
1 error

What is marker Interface?when it is used?


What is marker Interface?when it is used?

Marker interface is that interface which has no members in it.Marker interface is used as a tag to inform a message to the java compiler so that it can add special behaviour to the class implementing it. It is also known as null interface.

Definition:
“An interface is called a marker interface when it is provided as a handle by java interpreter to mark a class so that it can provide special behaviour to it at runtime and they do not have any method declarations”. 

It is used in the following scenario:
Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler. 
Java Marker Interface Examples
  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener

Java Interfaces Advantages and Disadvantages

Advantages:
 
1) through interfaces we can implement multiple inheritance in java.

2) Interfaces function to break up the complex designs and clear the dependencies between objects.
3) Interfaces makes your application loosely coupled.
 

Disadvantages:
 
1) Java interfaces are slower and more limited than other ones.
2) Interface should be used multiple number of times else there is hardly any use of having them

Java Interfaces

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. It is an interface through which multiple inheritance is implemented in Java. We can implements more than one interfaces in Java.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.  
one thing to be notice:

Class implements interfaces and interfaces extends  interfaces.
Class implements more than one interface and interface extends more than one interface.
 
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
interface Animal{
void eat();
void travel();
}
Interfaces have the following properties:
1.An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.
2.Each method in an interface is also implicitly abstract, so the abstract keyword is not needed
3.Methods in an interface are implicitly public.

Implementing Interfaces:
class Mammal implements Animal{
public void eat(){
 System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public static void main(String args[]){
      Mammal m = new Mammal();
      m.eat();
      m.travel();
   }
}
Output:
Mammal eats
Mammal travels
The class which implements the interface is necessary to implements its all methods..
Another definition of interface is:
An interface is a list of methods that must be defined by any class which implements that interface.
 
Subinterfaces:
Interfaces can extend several other interfaces, using the same formula as described below. For example
public interface A extends B, C
{
//interface  body
}

Difference between HibernateDaoSupport and HibernateTemplate

The biggest difference I know of is that the HibernateTemplate created by HibernateDaoSupport is allowed to create Hibernate sessions (allow create) if no session is bound to the current thread. You can change the value through the allow Create property on HibernateTemplate though. HibernateTemplate (a Hibernate class) is a property of the HibernateDaoSupport class (a Spring class).

Difference between APPLET and SERVELT

Ques.IN JAVA WHAT IS DIFFERENCE BETWEEN APPLET AND SERVELT?
Ans.1) Applet is client side application whereas Servlet is Server side application.
2) An applet is a Java program that runs within a Web browser on the client machine whereas a servlet runs on the Web server.
3) An applet can use the user interface classes like AWT or Swing while the servlet does not have a user interface.
4) Servlet is a server, Applet is a browser.
5) Applet is a downloadable small program which runs on the client side and executed by the client's java enabled browser or by the Apllet viewer. It doesn't need main() method to begin the execution,instead it begin's its lifecycle where the name of the class is passed to the Appletviewer.. The Applet's lifecycle have 4 methods.

init()-Where it can initialise itself
start()- It can start running
stop()-stop running
destroy()-Cleanup process happens

Applets are treated as untrused and they have a limited permission to run in the client browser

Servlet can be treated as Server-side applets.It runs in a servlet container which is deployed in the webserver. The lifecycle of the servlet have 3 methods.

init()

If an instance of the servlet does not exist, the Web container
a. Loads the servlet class
b. Creates the instance of the servlet class
c. Initialise the servlet instance by calling the init() method

service()-invokes this method by passing request and response object and a subsequent call to the same servlet is invoked as thread

destroy()-If the servlet container decides to remove the servlet, it calls this method

Difference between ArrayList and Vector

Q.What are key difference between ArrayList vs Vector in Java?
Ans.1) ArrayList is not thread safe where the Vector is i.e methods of vector are synchronized whereas ArrayList's methods are not.
2) ArrayList is fast as compared to Vector.
3) Vector and ArrayList both uses Array internally as data structure. They are dynamically resizable. Difference is in the way they are internally resized. By default, Vector doubles the size of its array when its size is increased. But, ArrayList increases by half of its size when its size is increased.
4) ArrayList has no default size while vector has a default size of 10.
5) In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. 

Why multiple Inheritance is not allowed in Java?

Q. Why multiple Inheritance is not allowed in Java?

A. We always want to extend multiple classes so that we inherits the features of the multiple classes.
For example:
class C extends A,B
{ }
but the above declaration is not valid in Java. In Java ,one class cannot extends from multiple classes. we can extend only from single class. But Java supports multilevel inheritance, means it will have multiple ancestors .For example

class C extends B{}
class B extends A{}

Here,  C class inherits the features from the multiple ancestors (A and B).

In C++ ,One can extend multiple classes simultaneously that is the declaration we have done for class A above is correct in case of C++.Capability of extending multiple classes is called as "Multiple Inheritance".Java creators thought a lot about to allow the multiple inheritance,but they were messed up after using the multiple inheritance. Like in this case ,if a class extended two classes and if both classes has methods in common then how the methods will be inherited and how we will come to know that which method is called of which class. That is why they excluded the multiple inheritance in Java. There is a famous problem which is faced during the multiple inheritance application called as "Deadly Diamond of Death".This is named so because the shape of class diagram which is formed after multiple inheritance implementation. The diamond is formed when classes B and C extend A ,and both B and C inherit methods from A. If class D extends both B and C,and both B and C have overridden the methods in class A,class D in theory has inherited the two different implementations of same method.


There is an indirect way by which you can implement the multiple inheritance in Java and this is through extending a class and implementing an interface just like following:-

class C extends B implements A{     //Here A is an interface
// implements methods
}

In this way you can get methods from both class and interface and you can override them according to your use. Remember all methods of interface needs to be overridden in implementing class.

this and super - Keywords

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.

The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference.Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.


class Counter {

    int i = 0;
    Counter increment() {
        i++;
        return this;
    }
    void print() {
        System.out.println("i = " + i);
    }
}

public class CounterDemo extends Counter {

    public static void main(String[] args) {
        Counter x = new Counter();
        x.increment().increment().increment().print();
    }
}

Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

Inheritance Advantages and Disadvantages

Advantages:-
 
One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common  code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be  refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of  code and smaller, simpler compilation units.

Inheritance can also make application code more flexible to change because classes that inherit from a common  superclass can be used interchangeably. If the return type of a method is superclass

Reusability -- facility to use public methods of base class without rewriting the same
Extensibility -- extending the base class logic as per business logic of the derived class
Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class

Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful  implementation of the base class method can be designed in the derived class.
 
Disadvantages:-
 
1.One of the main disadvantages of inheritance in Java (the same in other object-oriented languages) is the increased  time/effort it takes the program to jump through all the levels of overloaded classes. If a given class has ten levels of  abstraction above it, then it will essentially take ten jumps to run through a function defined in each of those classes

2.Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled.
This means one cannot be used independent of each other.

3. Also with time, during maintenance adding new features both base as well as derived classes are required to be  changed. If a method signature is changed then we will be affected in both cases (inheritance & composition)

4. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of using that  method.Here things can get a bit complicated in case of inheritance because our programs will still compile, but the  methods of the subclass will no longer be overriding superclass methods. These methods will become independent  methods in their own right.

What is not possible using java class inheritance?

What is not possible using java class Inheritance?
1 Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as  these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

Java Inheritance

Java Inheritance defines an is-a relationship between a super class and its sub classes.This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a general vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the super class and hence promotes code reuse. The subclass itself can add its own new behavior and properties. Object class is always at the top of any Class inheritance hierarchy.


class Box {

    double width;
    double height;
    double depth;
    Box() {
    }
    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }
    void getVolume() {
        System.out.println("Volume is : " + width * height * depth);
    }
}

public class MatchBox extends Box {

    double weight;
    MatchBox() {
    }
    MatchBox(double w, double h, double d, double m) {
        super(w, h, d);
        weight = m;
    }
    public static void main(String args[]) {
        MatchBox mb1 = new MatchBox(10, 10, 10, 10);
        mb1.getVolume();
        System.out.println("width of MatchBox 1 is " + mb1.width);
        System.out.println("height of MatchBox 1 is " + mb1.height);
        System.out.println("depth of MatchBox 1 is " + mb1.depth);
        System.out.println("weight of MatchBox 1 is " + mb1.weight);
    }
}


Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More