41-50 Flashcards

1
Q

How we can execute any code even before main method?

A

If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can a class be a super class and a sub-class at the same time?

A

If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How objects of a class are created if no constructor is defined in the class?

A

Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

In multi-threading how can we ensure that a resource isn’t used by multiple threads simultaneously?

A

In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can we call the constructor of a class more than once for an object?

A

Constructor is called automatically when we create an object using new keyword. It’s called only once for an object at the time of object creation and hence, we can’t invoke the constructor again for an object after its creation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can we have two methods in a class with the same name?

A

We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can we make copy of a java object?

A

We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.

Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What’s the benefit of using inheritance?

A

Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly