Subscribe For Free Updates!

We'll not spam mate! We promise.

Saturday 17 February 2018

QNS ON JAVA CONCEPTS, Why can a constructor in Java not be final, static or abstract


        1.   Why can a constructor in Java not be final, static or abstract?
Ø  Instance variables and methods are members of a class, but not Constructor. Constructors are property of a class.
Constructor cannot be overridden/inherited. It means like constructors cannot be call with objects like emp.details();
Ø  final is used for fixing, avoid overriding and inheriting.
Constructor cannot be final, because it can’t be inherited/overridden.
Ø  static is used for memory management, it means same variable or method will be shared between all instances of a class.
Constructor cannot be static because it cannot be call as method or variable, so no need to placing a static variable before constructor.
Ø  abstract means incomplete, for complementing it we need an implementation class/interface.
Constructor doesn’t required to be abstract because it doesn’t need to be implemented.
2.    Can abstract class have constructors in Java?
Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class,  constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class.
Now some interviewer, ask what is the purpose of constructor, if you can not instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside abstract class, and used by various implementation.
Also even if you don’t provide any constructor, compiler will add default no argument constructor in an abstract class, without that your subclass will not compile, since first statement in any constructor implicitly calls super(), default super class constructor in Java.
3.     Can abstract class implements interface in Java? does they require to implement all methods?
Yes, abstract class can implement interface by using implements keyword. Since they are abstract, they don’t need to implement all methods. It’s good practice to provide an abstract base class, along with an interface to declare Type. One example of this is java.util.List interface and corresponding java.util.AbstractList abstract class. Since AbstractList implements all common methods,  concrete implementations like LinkedList and ArrayList are free from burden of implementing all methods, had they implemented List interface directly. It’s best of both world, you can get advantage of interface for declaring type, and flexibility of abstract class to implement common behavior at one place. Effective Java has a nice chapter on how to use interface and abstract class in Java, which is worth reading.
4.     Can abstract class be final in Java?
No, abstract class can not be final in Java. Making them final will stop abstract class from being extended, which is the only way to use abstract class. They are also opposite of each other, abstract keyword enforces to extend a class, for using it, on the other hand, final keyword prevents a class from being extended. In real world also, abstract signifies incompleteness, while final is used to demonstrate completeness. Bottom line is, you can not make your class abstract and final in Java, at same time, it’s a compile time error.
5.     Can abstract class have static methods in Java?
Yes, abstract class can declare and define static methods, nothing prevents from doing that. But, you must follow guidelines for making a method static in Java, as it’s not welcomed in a object oriented design, because static methods can not be overridden in Java. It’s very rare, you see static methods inside abstract class, but as I said, if you have very good reason of doing it, then nothing stops you.
6.     Can you create instance of abstract class?
No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract,  you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.
7.     Is it necessary for abstract class to have abstract method?
No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class, e.g. now allowing to create any instance. By the way, it’s debatable whether you should have abstract method inside abstract class or interface. In my opinion, abstract class should have abstract methods, because that’s the first thing programmer assumes, when he see that class. That would also go nicely along principle of least surprise.
8.     Difference between abstract class and interface in Java?
abstract Classes
Interfaces
1
 abstract class can extend only one class or one abstract class at a time
 interface can extend any number of interfaces at a time
2
 abstract  class  can extend from a class or from an abstract class
 interface can extend only from an interface
3
 abstract  class  can  have  both  abstract and concrete methods
 interface can  have only abstract methods
4
 A class can extend only one abstract class
 A class can implement any number of interfaces
5
 In abstract class keyword ‘abstract’ is mandatory to declare a method as an abstract
 In an interface keyword ‘abstract’ is optional to declare a
 method as an abstract
6
 abstract  class can have  protected , public and public abstract methods
 Interface can have only public abstract methods i.e. by default
7
 abstract class can have  static, final  or static final  variable with any access specifier
 interface  can  have only static final (constant) variable i.e. by default
9.     When do you favor abstract class over interface?
This is the follow-up of previous interview questions on abstract class and interface. If you know syntactical difference, you can answer this question quite easily, as they are the one, which drives the decision. Since it’s almost impossible to add a new method on a published interface, it’s better to use abstract class, when evolution is concern. Abstract class in Java evolves better than interface. Similarly, if you have too many methods inside interface, you are creating pain for all it’s implementation, consider providing an abstract class for default implementation. This is the pattern followed in Java collection package, you can see AbstractList provides default implementation for List interface.
10.                    What is abstract method in Java?
An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration.  All method declared inside Java Interface are by default abstract. Here is an example of abstract method in Java
public void abstract printVersion();
Now, In order to implement this method, you need to extend abstract class and override this method.
11.                     Can abstract class contains main method in Java ?
Yes, abstract class can contain main method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.

12.                     What will happen if we define a concrete method in an interface?
·       By default interface methods are abstract.
·       if we declare any concrete method in an interface compile time error will come.
·       Error:  Abstract methods do not specify a body
13.                     Can we create non static variables in an interface?
·       No. We cannot create non static variables in an interface.
·       If we try to create non static variables compile time error comes.
·       By default members will be treated as public static final variables so it expects some value to be initialized.
14.                     When we need to use extends and implements?
·       A class will implements an interface.
·       A class will extends another class.
·       An interface extends another interface.
15.                    Can we declare constructor inside an interface?
·       No. Interfaces do not allow constructors.
·       The variables inside interfaces are static final variables means constants and we cannot create object from interface so there is no need of constructor in interface that is the reason interface doesn’t allow us to create constructor.

16.More example of instanceof operator

class Parent{}
 
class Child1 extends Parent{}
 
class Child2 extends Parent{}
 
class Test
{
  public static void main(String[] args)
  {
      Parent p =new Parent();
      Child1 c1 = new Child1();
      Child2 c2 = new Child2();
 
      System.out.println(c1 instanceof Parent);            //true
      System.out.println(c2 instanceof Parent);            //true
      System.out.println(p instanceof Child1);             //false
      System.out.println(p instanceof Child2);             //false
 
      p = c1;
      System.out.println(p instanceof Child1);             //true
      System.out.println(p instanceof Child2);             //false
 
      p = c2;
      System.out.println(p instanceof Child1);             //false
      System.out.println(p instanceof Child2);             //true
 
   }
 
}

17.When to use Abstract Methods & Abstract Class?

Abstract methods are usually declared where two or more subclasses are expected to do a similar thing in different ways through different implementations. These subclasses extend the same Abstract class and provide different implementations for the abstract methods.

Abstract classes are used to define generic types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class.

18.                Interface

Interface is a pure abstract class. They is syntactically similar to classes, but you cannot create instance of an Interface and their methods are declared without any body. Interface is used to achieve complete abstraction in Java. When you create an interface it defines what a class can do without saying anything about how the class will do it.

 

Rules for using Interface

·        Methods inside Interface must not be static, final, native or strictfp.
·        All variables declared inside interface are implicitly public static final variables(constants).
·        All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword.
·        Interface can extend one or more other interface.
·        Interface cannot implement a class.
·        Interface can be nested inside another interface.


19.Difference between an interface and an abstract class?

Abstract class
Interface
Abstract class is a class which contain one or more abstract methods, which has to be implemented by its sub classes.
Interface is a Java Object containing method declaration but no implementation. The classes which implement the Interfaces must provide the method definition for all the methods.
Abstract class is a Class prefix with an abstract keyword followed by Class definition.
Interface is a pure abstract class which starts with interface keyword.
Abstract class can also contain concrete methods.
Whereas, Interface contains all abstract methods and final variable declarations.
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes.
Interfaces are useful in a situation that all properties should be implemented.
                                                                                          

20.String Comparison

        String comparison can be done in 3 ways.
1.     Using equals() method
2.     Using == operator
3.     By CompareTo() method


Using equals() method

equals() method compares two strings for equality. Its general syntax is,
boolean equals (Object str)
It compares the content of the strings. It will return true if string matches, else returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2);    //true
s.equals(s1) ;   //false


Using == operator

== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(s1 == s2)     //true
test(s1 == s3)      //false

By compareTo() method

compareTo() method compares values and returns an int which tells if the string compared is less than, equal to or greater than the other string. It compares the String based on natural ordering i.e alphabetically. Its general syntax is,
int compareTo(String str)
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2);     //return -1 because s1 < s2 
s1.compareTo(S3);     //return 0 because s1 == s3 
s2.compareTo(s1);     //return 1 because s2 > s1

PLEASE SUBSCRIBE  IN ABOVE FIELED FOR MORE TUTORIAL/AND QNS!!