KEMBAR78
Basic Concepts of OOP | PDF | Inheritance (Object Oriented Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
28 views12 pages

Basic Concepts of OOP

The document provides an overview of Object-Oriented Programming (OOP) concepts, including its definition, the four pillars (encapsulation, inheritance, polymorphism, and abstraction), and key differences between classes and objects. It explains inheritance types, the significance of polymorphism, and the roles of composition and aggregation in OOP design. Additionally, it discusses interfaces, their differences from abstract classes, and the benefits of using multiple interfaces in Java.
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)
28 views12 pages

Basic Concepts of OOP

The document provides an overview of Object-Oriented Programming (OOP) concepts, including its definition, the four pillars (encapsulation, inheritance, polymorphism, and abstraction), and key differences between classes and objects. It explains inheritance types, the significance of polymorphism, and the roles of composition and aggregation in OOP design. Additionally, it discusses interfaces, their differences from abstract classes, and the benefits of using multiple interfaces in Java.
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/ 12

Basic Concepts of OOP

1. What is Object-Oriented Programming (OOP)?Answer:


OOP is a programming paradigm based on the concept of "objects," which can contain
data and methods. It promotes code reusability and modularity, making software easier to
maintain and extend.
2. What are the four pillars of OOP? Briefly explain each.Answer:
o Encapsulation: Wrapping data (fields) and code (methods) into a single unit
(class), with controlled access to the data via methods.
o Inheritance: Mechanism where one class acquires properties and behaviors of
another class.
o Polymorphism: Ability for a function, object, or method to take multiple forms.
o Abstraction: Hiding implementation details and exposing only functionality to
the user.
3. What is a class in Java? How is it different from an object?Answer:
A class is a blueprint from which objects are created. It defines attributes and behaviors.
An object is an instance of a class.
4. What is an object? How is an object created in Java?Answer:
An object is an instance of a class. It is created in Java using the new keyword.
Example: Car myCar = new Car();
5. What is the difference between a constructor and a method in Java?Answer:
A constructor is a special type of method used to initialize objects. It has the same name
as the class and no return type. A method performs actions or computations and may or
may not return a value.
6. What is the purpose of the new keyword in Java?Answer:
The new keyword is used to create an instance of a class, i.e., an object. It allocates
memory for the new object and calls the constructor.
7. Explain the difference between instance and static variables in a class.Answer:
o Instance variables belong to an instance (object) of a class. Each object has its
copy of the instance variables.
o Static variables belong to the class itself, shared by all instances of the class.
8. What is the difference between encapsulation and abstraction?Answer:
o Encapsulation is about hiding the internal state and requiring all interactions to
be performed through methods.
o Abstraction is about hiding complex implementation details and providing a
simplified interface.
9. What is the difference between data hiding and data encapsulation in
OOP?Answer:
o Data hiding refers to restricting access to certain data members of a class.
o Encapsulation bundles the data and methods that operate on the data into a single
unit (class).
10. What is meant by an "is-a" relationship and a "has-a" relationship in
OOP?Answer:
o "Is-a" relationship represents inheritance, where a class is a subtype of another
class. Example: Dog is a type of Animal.
o "Has-a" relationship represents composition or aggregation, where a class
contains references to other classes. Example: Car has an Engine.

Inheritance
1. What is inheritance in OOP? How is it implemented in Java?Answer:
Inheritance is a mechanism in OOP where one class (child/subclass) inherits fields and
methods from another class (parent/superclass). It is implemented using the extends
keyword.

class Animal {
void eat() {
System.out.println("Eating");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking");
}
}

2. How does Java support single inheritance? Provide an example.Answer:


Java supports single inheritance by allowing a class to inherit from only one superclass.
Example: class Dog extends Animal { ... }
3. What is multilevel inheritance? Show an example in Java.Answer:
Multilevel inheritance is a chain of inheritance where a class is derived from another
derived class.

class Animal {
void eat() {
System.out.println("Eating");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking");
}
}

class Puppy extends Dog {


void weep() {
System.out.println("Weeping");
}
}

4. What is hierarchical inheritance? Give a Java code example.Answer:


In hierarchical inheritance, multiple subclasses inherit from a single superclass.

class Animal {
void eat() {
System.out.println("Eating");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking");
}
}

class Cat extends Animal {


void meow() {
System.out.println("Meowing");
}
}

5. Why does Java not support multiple inheritance?Answer:


Java does not support multiple inheritance to avoid ambiguity, known as the Diamond
Problem, where a class can inherit conflicting implementations from multiple parent
classes.
6. What is the difference between method overriding and method overloading in the
context of inheritance?Answer:
o Method Overloading: Same method name, different parameter lists, within the
same class.
o Method Overriding: Subclass provides its implementation of a method defined
in the superclass.
7. What are the benefits of using inheritance in Java?Answer:
o Code reuse: Child classes reuse methods and fields of the parent class.
o Extensibility: New functionality can be added easily.
o Polymorphism: Parent class references can refer to child class objects.
8. Explain the use of the super keyword in inheritance with an example.Answer:
The super keyword is used to call the parent class's constructor or methods.

class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void sound() {
super.sound(); // Calls parent method
System.out.println("Dog barks");
}
}

9. Can private methods be inherited in Java? Explain with an example.Answer:


No, private methods cannot be inherited because they are not accessible outside their
class.
10. What is the final keyword, and how does it affect inheritance in Java?Answer:
The final keyword prevents a class from being subclassed or a method from being
overridden.

final class Vehicle { } // Cannot be extended

Polymorphism
1. What is polymorphism in OOP?Answer:
Polymorphism allows objects of different types to be treated as instances of the same
class through a common interface. It can be of two types: compile-time and runtime.
2. What is the difference between compile-time polymorphism and runtime
polymorphism in Java?Answer:
o Compile-time polymorphism (Method Overloading): Resolved during
compilation.
o Runtime polymorphism (Method Overriding): Resolved at runtime based on
the actual object.
3. How is method overloading implemented in Java? Provide an example.Answer:
Method overloading occurs when multiple methods in the same class have the same name
but different parameter types or counts.

class Calculator {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

4. What is method overriding in Java? Explain with an example.Answer:


Method overriding happens when a subclass provides a specific implementation of a
method that is already defined in its parent class.

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

5. What is the main advantage of using runtime polymorphism in Java?Answer:


The main advantage is flexibility, allowing the program to decide at runtime which
method to execute, promoting dynamic behavior and reducing code dependency.
6. Can constructors be overloaded in Java? If yes, how?Answer:
Yes, constructors can be overloaded by defining multiple constructors with different
parameter lists.
7. Can static methods be overridden in Java? Why or why not?Answer:
No, static methods cannot be overridden because they belong to the class, not the
instance, and are bound at compile time.
8. What is dynamic method dispatch in Java? Provide an example.Answer:
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at runtime, allowing runtime polymorphism.

class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

Animal a = new Dog();


a.sound(); // Calls Dog's sound method

9. What is the difference between upcasting and downcasting in the context of


polymorphism?Answer:
o Upcasting: Referring to a subclass object using a superclass reference.
o Downcasting: Casting a superclass reference to a subclass type.
10. What is the role of the instanceof keyword in polymorphism?Answer:
The instanceof keyword checks if an object is an instance of a specific class or
interface, ensuring type safety during downcasting.

if (obj instanceof Dog) {


Dog dog = (Dog) obj; // Downcasting
}
Specialization and Generalization
1. What is specialization in OOP? Provide a Java example.Answer:
Specialization is the process of creating new subclasses that extend or specialize a
general class.
Example: class Dog extends Animal { }
2. What is generalization in OOP? How is it different from specialization?Answer:
Generalization is the process of extracting shared characteristics from specific classes to
create a more general class. Specialization focuses on specific details, while
generalization focuses on common traits.
3. How does inheritance support the concept of specialization and generalization in
OOP?Answer:
Inheritance allows a subclass to specialize the behavior of a superclass (specialization)
and enables a superclass to generalize common behavior for its subclasses
(generalization).
4. What is the main difference between specialized and generalized classes in
Java?Answer:
o Specialized class focuses on more specific functionality.
o Generalized class defines common traits and behaviors.
5. Why is specialization referred to as "narrowing" and generalization as
"widening"?Answer:
Specialization is "narrowing" because it focuses on specific details, while generalization
is "widening" because it combines shared characteristics into a more general form.
6. How can an abstract class in Java support generalization?Answer:
An abstract class defines general behaviors that subclasses must implement, acting as a
generalized blueprint.
7. What is the purpose of a base class in the context of generalization?Answer:
A base class provides common functionality and properties for subclasses, acting as a
general template from which specialized classes can inherit.
8. Give an example of a general class in a real-world application (e.g., Animal
class).Answer:
The Vehicle class can be considered general. A more specialized class would be Car or
Bike.
9. How can specialization lead to better code reusability?Answer:
Specialization allows developers to extend existing general classes, reusing and
modifying common functionality without duplicating code.
10. What are the trade-offs of specialization and generalization in software
design?Answer:
o Specialization provides more specific functionality but can lead to duplication if
overused.
o Generalization promotes code reuse but can become too abstract, making it
harder to maintain and understand.
Composition
1. What is composition in OOP?Answer:
Composition is a design principle where one class contains references to objects of other
classes, representing a "has-a" relationship.
2. How does composition differ from inheritance in Java?Answer:
o Composition: Class A "has-a" Class B (A contains B).
o Inheritance: Class A "is-a" type of Class B (A extends B).
3. What does a "has-a" relationship mean in composition?Answer:
A "has-a" relationship means that one object contains another object. For example, a Car
has an Engine.
4. Provide an example of composition in Java.Answer:

class Engine {
void start() {
System.out.println("Engine started");
}
}

class Car {
Engine engine = new Engine();
void startCar() {
engine.start();
System.out.println("Car started");
}
}

5. What are the advantages of using composition over inheritance?Answer:


o Better flexibility (change member objects at runtime).
o Avoids problems like the diamond problem in inheritance.
o Promotes code reuse without tightly coupling classes.
6. Can a class have multiple compositions? Provide a code example.Answer:
Yes, a class can have multiple compositions by containing references to multiple objects.

class Engine { }
class Transmission { }

class Car {
Engine engine = new Engine();
Transmission transmission = new Transmission();
}

7. What is the difference between strong and weak composition?Answer:


o Strong composition: The contained object cannot exist without the containing
object.
o Weak composition (aggregation): The contained object can exist independently
of the containing object.
8. Explain why composition is often referred to as a "part-of" relationship.Answer:
Composition is called a "part-of" relationship because one object is a part of another (e.g.,
an engine is a part of a car).
9. How does object lifecycle relate to composition in Java?Answer:
In strong composition, when the containing object is destroyed, the contained object is
also destroyed. In weak composition (aggregation), the contained object can outlive the
container.
10. Can a composed object be shared among different classes in Java?Answer:
Yes, in aggregation (weak composition), a shared object can be used by multiple classes.

Aggregation
1. What is aggregation in OOP?Answer:
Aggregation is a type of association where one class contains references to another class,
but the contained object can exist independently.
2. How is aggregation different from composition?Answer:
o Aggregation: The contained object can exist independently.
o Composition: The contained object cannot exist without the containing object.
3. Explain with an example what a "has-a" relationship means in aggregation.Answer:
Example: A Library "has-a" Book, but the Book can exist independently of the Library.

class Book { }

class Library {
List<Book> books;
}

4. How does the lifecycle of objects differ in aggregation compared to


composition?Answer:
In aggregation, the contained objects can outlive the container, while in composition, the
contained objects are destroyed when the container is destroyed.
5. Provide a Java example where aggregation is used.Answer:

class Student { }

class Course {
List<Student> students;
}

6. Why is aggregation referred to as a weak association?Answer:


Aggregation is called weak association because the lifecycle of the contained object is
independent of the container.
7. Can an aggregated object exist independently of its parent class?Answer:
Yes, an aggregated object can exist independently and be used by other classes.
8. What is the role of constructors in setting up aggregation in Java?Answer:
Constructors can initialize the aggregation by passing the contained objects as
parameters.

class Course {
List<Student> students;
Course(List<Student> students) {
this.students = students;
}
}

9. What are the benefits of using aggregation in OOP design?Answer:


o Loose coupling between classes.
o Objects can be reused by multiple classes.
o Flexibility in the relationship between objects.
10. Explain how aggregation promotes loose coupling between classes.Answer:
Aggregation allows objects to exist independently of one another, reducing dependency
between classes, thus promoting loose coupling.

Interface
1. What is an interface in Java?Answer:
An interface is a reference type in Java, similar to a class, that can contain abstract
methods and constants. It provides a contract that classes must implement.
2. How is an interface different from an abstract class in Java?Answer:
o An interface can only have abstract methods (prior to Java 8). An abstract class
can have both abstract and concrete methods.
o A class can implement multiple interfaces but can only extend one abstract class.
3. Can an interface have method implementations in Java? Explain with an
example.Answer:
Yes, since Java 8, interfaces can have default and static method implementations.

interface Vehicle {
default void start() {
System.out.println("Vehicle started");
}
}

4. What are default methods in Java interfaces?Answer:


Default methods are methods in an interface that have a default implementation. They
allow interfaces to evolve without breaking existing implementations.
5. What is the benefit of multiple interfaces in Java?Answer:
Multiple interfaces allow a class to implement different functionalities and provide
flexibility through composition of behaviors.
6. Provide an example of how a class can implement multiple interfaces.Answer:
interface A {
void methodA();
}

interface B {
void methodB();
}

class C implements A, B {
public void methodA() { ... }
public void methodB() { ... }
}

7. Can an interface extend another interface in Java?Answer:


Yes, an interface can extend one or more interfaces.

interface A { }
interface B extends A { }

8. What is the difference between implements and extends in Java?Answer:


o implementsis used when a class implements an interface.
o extends is used when a class inherits another class or when an interface inherits
another interface.
9. Can an interface contain variables? If yes, what type of variables?Answer:
Yes, an interface can contain variables, but they must be public, static, and final.
10. What is the use of the functional interface in Java?Answer:
A functional interface contains exactly one abstract method and is used in lambda
expressions. Example: Runnable.

Library
1. What is a library in Java?Answer:
A library in Java is a collection of precompiled classes and methods that can be used in
applications to perform common tasks.
2. What is the purpose of the Java standard library?Answer:
The Java standard library provides a set of reusable classes and methods for tasks like file
I/O, string manipulation, networking, and more.
3. Give examples of classes from the Java standard library.Answer:
o java.util.ArrayList
o java.io.File
o java.lang.String
4. How do you import classes from a library in Java?Answer:
Use the import statement to include classes from a library.

import java.util.ArrayList;
5. What is the difference between import java.util.*; and import
java.util.ArrayList;?Answer:
o import java.util.*; imports all classes from the java.util package.
o import java.util.ArrayList; imports only the ArrayList class.
6. What is an external library in Java, and how do you add it to your project?Answer:
An external library is a set of classes and methods not part of the Java standard library.
You can add it to your project by including its JAR file in the classpath.
7. What is the role of a JAR file in Java libraries?Answer:
A JAR (Java ARchive) file bundles multiple Java classes and resources into a single file
for easier distribution and use as a library.
8. What is the difference between a package and a library in Java?Answer:
o A package is a namespace for organizing related classes.
o A library is a collection of classes, possibly from multiple packages, used to
perform common tasks.
9. Explain the purpose of third-party libraries in Java.Answer:
Third-party libraries provide additional functionality not available in the standard Java
library, saving development time by reusing code.
10. What are the advantages of using a library in Java development?Answer:
o Code reuse
o Reduced development time
o Access to optimized and tested code

Exceptions
1. What is an exception in Java?Answer:
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions.
2. What are the two main types of exceptions in Java?Answer:
o Checked Exceptions: Must be handled at compile time (e.g., IOException).
o Unchecked Exceptions: Runtime exceptions that do not need to be declared or
handled (e.g., NullPointerException).
3. What is the difference between throw and throws in Java?Answer:
o throw: Used to explicitly throw an exception.
o throws: Declares that a method can throw exceptions.
4. What is the purpose of a try-catch block in Java?Answer:
The try-catch block is used to handle exceptions. The code that might throw an
exception is placed inside the try block, and the catch block catches and handles the
exception.
5. What is the difference between finally and catch in exception handling?Answer:
o catch: Handles the exception.
o finally: Executes code regardless of whether an exception occurred or not, often
used for resource cleanup.
6. Provide an example of handling multiple exceptions using catch blocks.Answer:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Division by zero");
} catch (Exception e) {
System.out.println("General exception");
}

7. What is the purpose of the finally block in Java?Answer:


The finally block ensures that important code, such as resource cleanup, runs even if an
exception is thrown.
8. What is a custom exception in Java? How can you create one?Answer:
A custom exception is a user-defined exception that extends the Exception class.

class MyException extends Exception {


MyException(String message) {
super(message);
}
}

9. What is the difference between checked and unchecked exceptions in Java?Answer:


o Checked exceptions are checked at compile time, and the programmer is forced
to handle them.
o Unchecked exceptions occur at runtime and are not checked at compile time.
10. Can we handle multiple exceptions in a single catch block? Provide an
example.Answer:
Yes, Java 7 introduced multi-catch blocks.

try {
// Some code
} catch (IOException | SQLException e) {
System.out.println(e.getMessage());
}

You might also like