Quiz 3 Flashcards

1
Q

What is the difference between a static method and a non-static method?

A

A static method binds to the class rather than an instance (Driver Class). So we don’t really need an instance to access a static method (In order to use it’s properties in the Driver class we simply do it as “NameOfClass.ConstructorName()”.

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

When you should define a method as static?

A

Short Answer: When we do not need to have a state of the method and when some method looks like a jar/util method rather than a dependent on other instance members.

Long Answer:
Define static methods in the following scenarios only:

  • If you are writing utility classes and they are not supposed to be changed.
  • If the method is not using any instance variable.
  • If any operation is not dependent on instance creation.
  • If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
  • If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between a non-static field and a static field?

A

Same like static method, static fields bind to class rather than instance (Driver Class). So the value of this field will be same across all the instances. Where as non static field is different for each instance.

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

What does “this” represent in a class method?

A

This represents current instance of the class. “this” is a reference variable in Java that refers to the current object.

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

Does a constructor for a class constructs the object?

A

Yes it is. It constructs the object with whatever parameters passed to the constructer. It is possible that there are no arguments too.

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

Can an object live in the stack?

A

No. They lie in the heap memory.

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

When are parameters and local variables created and destroyed?

A

They get created when we invoke the method and all the parameters and local variables created in stack memory. They get destroyed once the method execution is done.

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