What is
constructor chaining how you achieved in Java?
Constructor is
chaining is the process of calling another constructor in same class or parent
class. To call constructor in the same class use this() and to call parent
class constructor use super(). Please have example below:
package
com.javahonk.constructorchain;
public class
Toyota extends Car {
Toyota() {
this("Java Honk");
}
Toyota(String name) {
super();
System.out.println(name);
}
public static void main(String args[]) {
new Toyota();
}
}
class Car {
Car() {
System.out.println("Car parent
class");
}
}
Output:
Important : What
really happens when calling the constructor. Please see below:
Toyota
constructor is invoked. When you create object in child class then every
constructor invokes the constructor of its superclass with an (implicit) call
to super()
Car constructor
is invoked because Car is super class of toyota (As you saw in above example
output as well)
Finally if no
more parent then Object constructor is invoked becuase Object is the superclass
of all classes, so class Car extends Object class if you extends it or not. At
this point we reached top of class hirarchy.
Object instance
variables are given their explicit values and its constructor completed.
Car instance
variables are given their explicit values (if any) and its constructor
completed.
Toyota instance
variables are given their explicit values (if any) and its constructor
completed.
Important : Why we need constructor chaining – Without
constructor chaining parent wouldn’t know about children and parent must be
crated before child.
Does Constructor
creates the object ?
New operator in
Java creates objects. Constructor is the later step in object creation.
Constructor's job is to initialize the members after the object has reserved
memory for itself.
The No-Arg
Constructor
The constructor
which takes no arguments is called the no-arg constructor . For example, the no-arg constructor is
invoked when a variable is declared like this:
Complex c = new
Complex ();
If there are no
constructors defined in a Java class, the Java compiler provides a default
no-arg constructor . The default no-arg
constructor does nothing. The fields simply the retain their initial, default
values.
program56555
Program: Complex
constructors.
Program gif gives
an implementation for the no-arg constructor. of the Complex class (lines
12-13). This constructor simply invokes the method called this. In Java one
constructor can invoke another constructor by calling the this method as its
first executable statement. In this case, the no-arg constructor invokes the
two-arg constructor to set both real and imag fields to zero.
Why do abstract
classes have constructors in Java?
constructor is
used for constructor chaining in java to current class constructor to the
parent class constructor with the implicit keyword super(); which may be stated
or may not bestated . super keyword is
the responsibility of compilor. compilor search constructor in your existing
class if compilor found constructor then it chek have you written super in your
constructor if you have written so compilor will not write super.If you didn't
write super then responsibility of constructructor to write super on your
existing constructor for constructor chaining to parent class constructor .
you know that
every class is a subclass of class object.means every class constructor have to
do constructor chaining with object class constructor with super keyword. No
matter class is abstract or not. thats why abstract class has constructor on it.
Is the default
constructor in Java always empty?
No, Default
constructor in java contains the initialization block to initialize the class
members to their default values if their values are not defined like
initializing integer to zero.
Wherever compiler
does not find any valid constructor in your class then it inserts default
constructor in your class automatically, which contains the initialization
block.That is a reason, you can create objects without having default
constructor in your class. As when object is created,default constructor is
called which is generated automatically.
Can an interface
have constructors?
Sorry, not
possible as constructor is nothing but a concrete (non-abstract) method that
carries a body. Interface cannot have concrete methods.
What access
modifiers a constructor cannot be?
"A
constructor cannot be abstract, static, final, native, strictfp, or
synchronized".
What is a
singleton class? Give a practical example of its usage.
A singleton class
in java can have only one instance and hence all its methods and variables
belong to just
one instance. Singleton class concept is useful for the situations when there
is a
need to limit the
number of objects for a class.
The best example
of singleton usage scenario is when there is a limit of having only one
connection to a
database due to some driver limitations or because of any licensing issues.
What is the
difference between Break and Continue statement in Java?
Using break
statement : When a break statement is encountered inside a loop, the loop is
terminated and program control resumes at the next statement following the
loop.
Using continue
statement : When a continue statement is encountered inside the body of a loop,
remaining statements are skipped and loop proceeds with the next iteration.
Here is a simple example.
Here is a simple
example:
class
BreakAndContinue
{
public static void main(String args[])
{
// Illustrating break statement
(execution stops when value of i becomes to 4.)
System.out.println("Break
Statement\n....................");
for(int i=1;i<=5;i++)
{
if(i==4) break;
System.out.println(i);
}
// Illustrating continue statement
(execution skipped when value of i becomes to 1.)
System.out.println("Continue
Statement\n....................");
for(int i=1;i<=5;i++)
{
if(i==1) continue;
System.out.println(i);
}
}
}
Output:
Break Statement :
1
2
3
Continue
Statement
2
3
4
5
Why do abstract
classes have constructors in Java?
constructor is
used for constructor chaining in java to current class constructor to the
parent class constructor with the implicit keyword super(); which may be stated
or may not bestated . super keyword is
the responsibility of compilor. compilor search constructor in your existing
class if compilor found constructor then it chek have you written super in your
constructor if you have written so compilor will not write super.If you didn't
write super then responsibility of constructructor to write super on your
existing constructor for constructor chaining to parent class constructor .
come to your
qustion
you know that
every class is a subclass of class object.means every class constructor have to
do constructor chaining with object class constructor with super keyword. No
matter class is abstract or not. thats why abstract class has constructor on it.
What happens if a
class doesn't implement all the methods defined in the interface?
When a class is
defined to implement an interface, the class must provide definitions of all
the methods defined in the interface. Otherwise, you will get compiler time
error.
A class must
implement all methods of the interface, unless the class is declared as
abstract. There are only two choices:
Implement every
method defined by the interface.
Declare the class
as an abstract class, as a result, forces you to subclass the class (and
implement the missing methods) before you can create any objects.
The only case the
class do not need to implement all methods in the interface is when any class
in its inheritance tree has already provided concrete (i.e., non-abstract)
method implementations then the subclass is under no obligation to re-implement
those methods. The supclass may not implement the interface at all and just
method signature is matched. For example,
interface
MyInterface {
void m() throws NullPointerException;
}
class SuperClass
{
//NOTE :
SuperClass class doesn't implements MyInterface interface
public void m() {
System.out.println("Inside SuperClass
m()");
}
}
class SubClass
extends SuperClass implements MyInterface {
}
public class
Program {
public static void main(String args[]) {
SubClass s = new SubClass();
s.m();
}
}
The above code
shows a concrete class SubClass that declares that it implements an interface
MyInterface, but doesn't implement the m() method of the interface. The code is
legal because its parent class SuperClass implements a method called m() with
the same name as the method in the interface.
What is the
difference between Abstract Class and Interface in java?
Abstract class vs
Interface in Java
1) First and the
major difference between abstract class and an interface is that an abstract
class is a class while the interface is an interface, means by extending the
abstract class you cannot extend another class because Java does not support
multiple inheritances but you can implement multiple inheritance in Java.
2) The second
difference between interface and abstract class in Java is that you cannot
create a non-abstract method in an interface, every method in an interface is
by default abstract, but you can create a non-abstract method in abstract
class. Even a class which doesn't contain any abstract method can be made
abstract by using the abstract keyword.
3) The third
difference between abstract class vs interface in Java is that interface is
better suited for Type declaration and abstract class is more suited for code
reuse and evolution perspective
4) The fourth
difference between abstract class and interface in Java is that abstract class
are slightly faster than interface because interface involves a search before
calling any overridden method in Java. This is not a significant difference in
most of the cases but if you are writing a time critical application then you
may not want to leave any stone unturned.
5) Another
notable difference between interface and abstract class is that when you add a
new method in existing interface it breaks all its implementation and you need
to provide an implementation in all clients which is not good. By using an
abstract class you can provide a default implementation for a new method in the
superclass without breaking existing clients.
Can we declare
abstract method as final?
No, we cannot
declare abstract method as final. We have to provide implementation to abstract
methods in subclasses.
Can we declare
Abstract Static Method?
Before answering
this question, let us brief about abstract methods.
Following points
are to be remembered with abstract methods.
1. First of all,
an abstract method cannot be static as static methods should have a body and
abstract methods should not.
2. An abstract
class can have the following combinations of methods.
a. All methods abstract
b. All methods concrete (non-abstract)
c. A mixture of abstract and non-abstract
methods
Observe, it the
above list Abstract Static Method does not exist.
Now we have a
different question to be answered.
Can an abstract class have static methods?
Yes, definitely
can have as a static method is special flavor of concrete method. We know a
static method can be called with object name (not possible here), class name and
directly without the help of an object. Following program explains.
abstract class
Test
{
public static void display()
{
System.out.println("Hello 1");
}
}
public class Demo
extends Test
{
public static void main(String args[])
{
display();
Test.display();
}
}
abstract class
Test
{
public static void display()
{
System.out.println("Hello 1");
}
}
public class Demo
extends Test
{
public static void main(String args[])
{
display();
Test.display();
}
}
In the above
code, the display() method is declared static. It is called in the subclass
directly and with abstract class name.
Can an interface
have static methods?
No, impossible.
All methods of an interface must be public and abstract (by default takes also
if not mentioned). As static methods should have a body, the interface methods
cannot be static.
What is
System.out.println
System.out.println
is a Java statement that prints the argument passed, into the System.out which
is generally stdout.
System – is a
final class in java.lang package. As per javadoc, “…Among the facilities
provided by the System class are standard input, standard output, and error
output streams; access to externally defined properties and environment
variables; a means of loading files and libraries; and a utility method for
quickly copying a portion of an array…“
out – is a static
member field of System class and is of type PrintStream. Its access specifiers
are public final. This gets instantiated during startup and gets mapped with
standard output console of the host. This stream is open by itself immediately
after its instantiation and ready to accept data.
println – is a
method of PrintStream class. println prints the argument passed to the standard
console and a newline. There are multiple println methods with different
arguments (overloading). Every println makes a call to print method and adds a
newline. print calls write() and the story goes on like that.

No comments:
Post a Comment