0% found this document useful (0 votes)
5 views

OOPtheroy

The document provides an overview of key concepts in Java, including objects, classes, interfaces, polymorphism, generics, and inheritance. It explains the roles of constructors, the nature of interfaces, methods of achieving polymorphism, and the advantages of using generics. Additionally, it discusses inheritance types and restrictions, highlighting the importance of these concepts in Java programming.

Uploaded by

b.biancapopescu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

OOPtheroy

The document provides an overview of key concepts in Java, including objects, classes, interfaces, polymorphism, generics, and inheritance. It explains the roles of constructors, the nature of interfaces, methods of achieving polymorphism, and the advantages of using generics. Additionally, it discusses inheritance types and restrictions, highlighting the importance of these concepts in Java programming.

Uploaded by

b.biancapopescu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

OBJECTS AND CLASSES

All classes have at least one constructor. If a class does not explicitly declare any, the Java
compiler automatically provides a no-argument constructor, also called the default constructor.
This default constructor calls the class parent’s no-argument constructor (as it contain only one
statement, i.e. super();), or the Object class constructor if the class has no other parent (as
Object class is parent of all classes either directly or indirectly).

INTERFACES
1. What is an interface in Java?
Ans: An interface in Java is a mechanism that is used to achieve complete abstraction. It is
basically a kind of class that contains only constants and abstract methods.
2. Can we define private and protected modifiers for data members (fields) in interfaces?
Ans: No, we cannot define private and protected modifiers for variables in interface because
the fields (data members) declared in an interface are by default public, static, and final.
3. Which modifiers are allowed for methods in an Interface?
Ans: Only abstract and public modifiers are allowed for methods in interfaces.
4. Suppose A is an interface. Can we create an object using new A()?
Ans: No, we cannot create an object of interface using new operator. But we can create a
reference of interface type and interface reference refers to objects of its implementation
classes.
5. Can we define an interface with a static modifier?
Ans: Yes, from Java 8 onwards.
6. Suppose A is an interface. Can we declare a reference variable a with type A like this: A a;
Ans: Yes.
7. Can an interface extends another interface in Java?
Ans: Yes.
8. Can an interface implement another interface?
Ans: No.
9. Is it possible to define a class inside an interface?
Ans: Yes.
10. Can an interface extend multiple interfaces?
Ans: Yes.
11. Can an interface has instance and static blocks?
Ans: No.
12. What happens if a class has implemented an interface but has not provided
implementation for that method defined in Interface?
Ans: The class has to be declared with an abstract modifier. This will be enforced by the Java
compiler.
13. Why an Interface method cannot be declared as final in Java?
Or, Can a method within an interface be marked as final?
Ans: Not possible. Doing so will result the compilation error problem. This is because a final
method cannot be overridden in java. But an interface method should be implemented by
another class.
14. Can an interface be final?
Ans: No. Doing so will result compilation error problem.
15. Why an interface cannot have a constructor?
Ans: Inside an interface, a constructor cannot be called using super keyword with hierarchy.
16. Why an Interface can extend more than one Interface but a Class can’t extend more than
one Class?
Ans: We know that Java doesn’t allow multiple inheritance because a class extends only one
class. But an Interface is a pure abstraction model. It does not have inheritance hierarchy like
classes.
17. What is the use of interface in Java?
Ans: There are many reasons to use interface in java. They are as follows:
a. An interface is used to achieve fully abstraction.
b. Using interfaces is the best way to expose our project’s API to some other project.
c. Programmers use interface to customize features of software differently for different objects.
d. By using interface, we can achieve the functionality of multiple inheritance.
18. Is it necessary to implement all abstract methods of an interface?
Ans: Yes.
19. Can we define a variable in an interface? What type it should be?
Ans: Yes, we can define variable in an interface that must be implicitly static and final.
20. Can we re-assign a value to a variable of interface?
Ans: No, variables defined inside the interface are static and final by default. They are just like
constants. We can’t change their value once they got.
21. What is the difference between abstract class and interface in Java?
Ans: An abstract class allows you to create functionality that subclasses can implement or
override. An interface only allows you to define functionality, not implement it. And whereas a
class can extend only one abstract class, it can take advantage of multiple interfaces.
22. Do abstract classes have a constructor?
Constructor is always called by its class name in a class itself. A constructor is used to initialize
an object not to build the object. As we all know abstract classes also do have a constructor.
23. What is the difference between class and interface in Java?
24. What is a Nested interface?
Ans: An interface declared inside another interface is called nested interface. By default, it is
static in nature. It is also known as static interface.
25. Can we reduce the visibility of interface method while overriding?
Ans: No, while overriding any interface methods, we must use public only. This is because all
interface methods are public by default.
26. Can we define an interface inside a method as local member?
Ans: No.
POLYMORPHISM
1. What is Polymorphism in Java OOPs?
Ans: Polymorphism in java is one of the core concepts of oop system. Polymorphism means
“many forms” in Greek. That is one thing that can take many forms.
Polymorphism is a concept by which we can perform a single task in different ways. That is,
when a single entity (object) behaves differently in different cases, it is called polymorphism.
In other words, if a single object shows multiple forms or multiple behaviours, it is called
polymorphism.
3. What are different ways to achieve or implement polymorphism in Java?
Ans: Polymorphism in Java can be primarily achieved by subclassing or by implementing an
interface. The subclasses can have their own unique implementation for certain features and
can also share some of the functionality through inheritance.
5. What are the advantages of Polymorphism?
Ans: There are the following advantages of polymorphism in java:
a. Using polymorphism, we can achieve flexibility in our code because we can perform various
operations by using methods with the same names according to requirements.
b. The main benefit of using polymorphism is when we can provide implementation to an
abstract base class or an interface.
6. What are the differences between Polymorphism and Inheritance in Java?
Ans: The differences between polymorphism and inheritance in java are as follows:
a. Inheritance represents the parent-child relationship between two classes. On the other hand,
polymorphism takes the advantage of that relationship to make the program more dynamic.
b. Inheritance helps in code reusability in child class by inheriting behaviour from parent class.
On the other hand, polymorphism enables child class to redefine already defined behaviour
inside parent class.
Without polymorphism, it is not possible for a child class to execute its own behaviour.
21. What is Binding in Java?
Ans: The connecting (linking) between a method call and method definition is called binding in
java.
22. What are the types of binding in Java?
Ans: There are two types of binding in java. They are as follows:
a. Static Binding (also known as Early Binding).
b. Dynamic Binding (also known as Late Binding).
23. What is Static binding in Java?
Ans: The binding that happens during compilation is called static binding in java. This binding is
resolved at the compiled time by the compiler.
24. How Java compiler performs static binding?
Ans: Java compiler just checks which method is going to be called through reference variable
and method definition exists or not.
It does not check the type of object to which a particular reference variable is pointing to it.
25. Why static binding is also called early binding in Java?
Ans: Static binding is also called early binding because it takes place before the program
actually runs.
26. Give an example of static binding.
Ans: An example of static binding is method overloading.
27. What is Dynamic binding in Java?
Ans: The binding which occurs during runtime is called dynamic binding in java. This binding is
resolved based on the type of object at runtime.
28. How JVM performs dynamic binding in Java?
Ans: In the dynamic binding, the actual object is used for binding at runtime. JVM resolved the
method calls based on the type of object at runtime. The type of object cannot be determined
by the compiler.
29. Why Dynamic binding is also called late binding in java?
Ans: Dynamic binding is also called late binding or runtime binding because binding occurs
during runtime.
30. Give an example of dynamic binding in Java.
Ans: An example of dynamic binding is method overriding.
32. Why binding of private, static, and final methods are always static binding in Java?
Ans: Static binding is better performance-wise because java compiler knows that all such
methods cannot be overridden and will always be accessed by object reference variable.
Hence, the compiler doesn’t have any difficulty in binding between a method call and method
definition. That’s why binding for such methods is always static.
GENERICS
1. What Is a Generic Type Parameter?
Type is the name of a class or interface. As implied by the name, a generic type parameter is
when a type can be used as a parameter in a class, method or interface declaration.
public interface Consumer{
public void consume(String parameter)
}
In this case, the method parameter type of the consume() method is String. It is not
parameterized and not configurable.
Now let's replace our String type with a generic type that we will call T. It is named like this by
convention:
public interface Consumer<T> {
public void consume(T parameter)}
When we implement our consumer, we can provide the type that we want it to consume as an
argument. This is a generic type parameter:
public class IntegerConsumer implements Consume r<Integer> {
public void consume(Integer parameter)}
In this case, now we can consume integers. We can swap out this type for whatever we require.
2. What Are Some Advantages of Using Generic Types?
One advantage of using generics is avoiding casts and provide type safety. This is particularly
useful when working with collections. Let's demonstrate this:
List list = newArrayList();
list.add("foo");
Object o = list.get(0);
String foo = (String) o;
In our example, the element type in our list is unknown to the compiler. This means that the
only thing that can be guaranteed is that it is an object. So when we retrieve our element,
an Object is what we get back. As the authors of the code, we know it's a String, but we have to
cast our object to one to fix the problem explicitly. This produces a lot of noise and boilerplate.
Now, let's try repeating ourselves, this time using generics:
List<String> list = newArrayList<>();
list.add("foo");
String o = list.get(0); // No cast
Integer foo = list.get(0); // Compilation error
As we can see, by using generics we have a compile type check which
prevents ClassCastExceptions and removes the need for casting.
The other advantage is to avoid code duplication. Without generics, we have to copy and
paste the same code but for different types. With generics, we do not have to do this. We can
even implement algorithms that apply to generic types.
3. What Is Type Erasure?
It's important to realize that generic type information is only available to the compiler, not the
JVM. In other words, type erasure means that generic type information is not available to the
JVM at runtime, only compile time.
4. How Does a Generic Method Differ from a Generic Type?
A generic method is where a type parameter is introduced to a method, living within the
scope of that method. Let's try this with an example:
public static<T> T returnType(T argument){
return argument; }
We've used a static method but could have also used a non-static one if we wished. By
leveraging type inference (covered in the next question), we can invoke this like any ordinary
method, without having to specify any type arguments when we do so.
5. What Is a Bounded Type Parameter?
So far all our questions have covered generic types arguments which are unbounded. This
means that our generic type arguments could be any type that we want.
When we use bounded parameters, we are restricting the types that can be used as generic
type arguments.
As an example, let's say we want to force our generic type always to be a subclass of animal:
public abstract class Cage<T extends Animal> {
abstract void addAnimal(T animal)}
By using extends, we are forcing T to be a subclass of animal. We could then have a cage of
cats:
Cage<Cat> catCage;
But we could not have a cage of objects, as an object is not a subclass of an animal:
Cage<Object> objectCage; // Compilation error
One advantage of this is that all the methods of animal are available to the compiler. We know
our type extends it, so we could write a generic algorithm which operates on any animal. This
means we don't have to reproduce our method for different animal subclasses:
publicvoidfirstAnimalJump(){
T animal = animals.get(0);
animal.jump();}
6. Is It Possible to Declared a Multiple Bounded Type Parameter?
Yes
7. What Is a Wildcard Type?
A wildcard type represents an unknown type. It's detonated with a question mark as follows:
public static void consumeListOfWildcardType(List<?> list)
Here, we are specifying a list which could be of any type. We could pass a list of anything into
this method.
INHERITANCE
1. What is Inheritance in Java?
Ans: The technique of creating a new class by using an existing class functionality is called
inheritance in Java. In other words, inheritance is a process where a child class acquires all the
properties and behaviours of the parent class.
2. Why do we need to use inheritance?
We can reuse the code from the base class.
Using inheritance, we can increase features of class or method by overriding.
Inheritance is used to use the existing features of class.
It is used to achieve runtime polymorphism i.e. method overriding.
3. What is Is-A relationship in Java?
Ans: Is-A relationship represents Inheritance. It is implemented using the “extends” keyword. It
is used for code reusability.
4. What is super class and subclass?
Ans: A class from where a subclass inherits features is called superclass. It is also called base
class or parent class.
A class that inherits all the members (fields, method, and nested classes) from other class is
called subclass. It is also called a derived class, child class, or extended class.
5. How is Inheritance implemented/achieved in Java?
Ans: Inheritance can be implemented or achieved by using two keywords:
1. extends: extends is a keyword that is used for developing the inheritance between two
classes and two interfaces.
2. implements: implements keyword is used for developing the inheritance between a
class and interface.
6. Write the syntax for creating the subclass of a class?
Ans: A subclass can be created by using the “extends” keyword.
7. Which class in Java is superclass of every other class?
Ans: Object class.
8. Can a class extend itself?
Ans: No.
9. Can we assign superclass to subclass?
Ans: No.
10. Can a class extend more than one class?
Ans: No.
11. Are constructor and instance initialization block inherited to subclass?
Ans: No, but they are executed while creating an object of the subclass.
12. Are static members inherited to subclass in Java?
Ans: Static block cannot be inherited to its subclass. A static method of superclass is inherited to
the subclass as a static member and non-static method is inherited as a non-static member
only.
13. Can we extend (inherit) final class?
Ans: No.
14. Can a final method be overridden?
Ans: No.
15. Can we inherit private members of base class to its subclass?
Ans: No.
16. What is order of calling constructors in case of inheritance?
Ans: From the top to down hierarchy.
17. Which keyword do you use to define a subclass?
Ans: extends keyword.
18. What are the advantages of inheritance in Java?
• We can minimize the length of duplicate code in an application by putting the common
code in the superclass and sharing it amongst several subclasses.
• Due to reducing the length of code, the redundancy of the application is also reduced.
• Inheritance can also make application code more flexible to change.
19. What are the various forms of inheritance available in Java?
Ans: The various forms of inheritance to use are single inheritance, hierarchical inheritance, and
multilevel inheritance.
20. What is single inheritance and multi-level inheritance?
Ans: When one class is extended by only one class, it is called single level inheritance. In single-
level inheritance, we have just one base class and one derived class.
A class which is extended by a class and that class is extended by another class forming chain
inheritance is called multilevel inheritance.
21. How does Multiple inheritance implement in Java?
Ans: Multiple inheritance can be implemented in Java by using interfaces. A class cannot extend
more than one class but a class can implement more than one interface.
22. What is Hybrid inheritance in java? How will you achieve it?
Ans: A hybrid inheritance in java is a combination of single and multiple inheritance. It can be
achieved through interfaces.
23. How will you restrict a member of a class from inheriting its subclass?
Ans: We can restrict members of a class by declaring them private because the private
members of superclass are not available to the subclass directly. They are only available in their
own class.
24. Can we access subclass members if we create an object of superclass?
Ans: No.
25. Can we access both superclass and subclass members if we create an object of subclass?
Ans: Yes.
26. Is interface inherited from the Object class?
Ans: No.
EVENT HANDLING
1. What is an adapter class?
An adapter class provides an empty implementation of all methods in an event listener
interface.
Adapter classes are useful when you want to receive and process only some of the events that
are handled by a particular event listener interface.
You can define a new class to act listener by extending one of the adapter classes and
implementing only those events in which you are interested.
For example, the MouseAdapter class has two methods, mouseDragged() and mouseMoved().
2. What interface is extended by AWT event listener?
All AWT event listeners extend the java.util.EventListener interface.
EXCEPTION HANDLING
1. What is an exception?
Exception is an abnormal condition which occurs during the execution of a program and
disrupts normal flow of the program. This exception must be handled properly. If it is not
handled, program will be terminated abruptly.
2. How the exceptions are handled in Java?
Exceptions in Java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception are kept in
this block.
catch block : This block catches the exceptions occurred in the try block.
finally block : This block is always executed whether exception is occurred in the try block or not
and occurred exception is caught in the catch block or not.
3. What is the difference between error and exception in Java?
Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Whereas exceptions are mainly
caused by the application itself. For example, NullPointerException occurs when an application
tries to access null object.
4. Can we keep other statements in between try, catch and finally blocks?
No.
5. Can we write only try block without catch and finally blocks?
No, It shows compilation error.
6. There are three statements in a try block – statement1, statement2 and statement3.
After that there is a catch block to catch the exceptions occurred in the try block.
Assume that exception has occurred in statement2. Does statement3 get executed or
not?
No. Once a try block throws an exception, remaining statements will not be executed. control
comes directly to catch block.
7. What is unreachable catch block error?
When you are keeping multiple catch blocks, the order of catch blocks must be from most
specific to most general ones. i.e. sub classes of Exception must come first and super classes
later. If you keep super classes first and sub classes later, compiler will show unreachable catch
block error.
9) What are run time exceptions in Java. Give example?
The exceptions which occur at run time are called as run time exceptions. These exceptions are
unknown to compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are run
time exceptions. These exceptions are unchecked type of exceptions. For
example, NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOf
BoundException, StackOverflowError etc.
10) What is OutOfMemoryError in Java?
OutOfMemoryError is the sub class of java.lang.Error which occurs when JVM runs out of
memory.
11) what are checked and unchecked exceptions in java?
Checked exceptions are the exceptions which are known to compiler. These exceptions are
checked at compile time only. Hence the name checked exceptions. These exceptions are also
called compile time exceptions. Because, these exceptions will be known during compile time.
Unchecked exceptions are those exceptions which are not at all known to compiler. These
exceptions occur only at run time. These exceptions are also called as run time exceptions. All
sub classes of java.lang.RunTimeException and java.lang.Error are unchecked exceptions.
13) Can we keep the statements after finally block If the control is returning from the finally
block itself?
No.
14) Does finally block get executed If either try or catch blocks are returning the control?
Yes, finally block will be always executed no matter what.
15) Can we throw an exception manually? If yes, how?
Yes, we can throw an exception manually using throw keyword.
21) What is ClassCastException in Java?
ClassCastException is a RunTimeException which occurs when JVM unable to cast an object of
one type to another type.
23) What is StackOverflowError in Java?
StackOverflowError is an error which is thrown by the JVM when stack overflows.
24) Can we override a super class method which is throwing an unchecked exception with
checked exception in the sub class?
No.
26) Which class is the super class for all types of errors and exceptions in Java?
java.lang.Throwable.
28) What is the use of printStackTrace() method?
printStackTrace() method is used to print the detailed information about the exception
occurred.
29) Give some examples to checked exceptions?
ClassNotFoundException, SQLException, IOException
30) Give some examples to unchecked exceptions?
NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

You might also like