Chapter 4 - OOP in General Flashcards

1
Q

OOP meaning

A

Object-Oriented Programming (OOP) is a programming paradigm that emphasizes the organization of code and data into self-contained units called objects. Java is an object-oriented programming language, and it is designed to support OOP principles. OOP promotes the use of objects to structure and manage code, making it easier to design, develop, and maintain software.

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

Class and its features

A

A class is a blueprint or template for creating objects. It defines the properties (data members or fields) and behaviors (methods) that objects of that class will possess.

Attributes (Properties):

Methods (Functions):Constructor: Access Modifiers:

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

Object and its features

A

Objects are instances of classes, and they encapsulate both data (attributes or properties) and behaviors (methods or functions) that are associated with the class they belong to. Objects are used to model and interact with entities in a software system, making OOP a powerful and intuitive way to design and structure code.

Instance of a Class: An object is created based on a class, which serves as a blueprint or template for defining the object’s structure and behavior. Multiple objects of the same class can be created, each with its own set of attributes and state.

Attributes (Properties): Objects have attributes that represent their state or characteristics. These attributes are data members or variables within the class and define what data an object can store. For example, a Person object may have attributes like name, age, and address.

Methods (Behaviors): Objects have methods, which are functions defined within the class. Methods specify the actions or behaviors that objects can perform. Methods can operate on the object’s attributes and implement specific functionalities. For instance, a Car object may have methods like startEngine(), accelerate(), and brake().

Identity: Each object has a unique identity or reference that distinguishes it from other objects. This identity is often represented by a memory address or a reference in the program. This identity is usually represented by a memory address or a reference.

State: The state of an object refers to the values of its attributes at a particular point in time. It reflects the object’s current data.

Behavior: An object’s behavior is defined by its methods and describes what it can do or how it can respond to messages or requests from other objects.

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

Object type

A

the term “object type” refers to the specific class or data type of an object.

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

write class

A

[access_modifier] class ClassName {}

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

Class access modifiers

A

Public
Default
Private
Protected

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

Public access modifier of class

A

The class, field, method, or constructor declared as public can be accessed from anywhere in your code, both within and outside the package where the class is defined.
It has the widest scope and the least restrictive access level.

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

Default access Modifier of class

A

A class with default access is accessible to other classes and components within the same package, but it’s not visible to classes outside that package.

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

Private access modifier of class

A

A class declared as private can only be accessed within the same class. It is the most restrictive access modifier for classes and is rarely used for classes themselves.

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

Protected access modifier of class

A

Members declared as protected are accessible within the class they are defined in and in its subclasses. They are not accessible from outside the class hierarchy.

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

What is constructor?

A

A constructor in Java is a special type of method that is used to initialize objects. It is called automatically when an object of a class is created. The primary purpose of a constructor is to set up the initial state of an object, allocate memory for the object, and perform any necessary initialization tasks.

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

What can you tell me about name and return type of constructor?

A

A constructor must have the same name as the class it belongs to. It’s called automatically when an object is created using the new keyword.

Constructors do not have a return type, not even void. They are implicitly assumed to return an instance of the class.

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

Constructor overloading? why we need it?

A

You can define multiple constructors in a class with different parameter lists. This is known as constructor overloading.

it allowss Initialization Flexibility: Different situations may require objects to be initialized with different sets of initial values. By providing multiple constructors, you give users of your class the flexibility to create objects with the initialization data that best suits their needs.

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

Default constructor and why is better custom one?

A

A default constructor in Java is a constructor that is automatically provided by the Java compiler when a class doesn’t explicitly define any constructors. The default constructor has no arguments and typically initializes instance variables to default values (e.g., numeric fields to 0, object references to null, etc.). Its purpose is to ensure that objects of the class can still be created without requiring any special initialization parameters.

Custom constructors allow you to provide flexibility when creating objects. You can offer multiple constructor options with different parameter sets, enabling users of your class to choose the one that best suits their needs. This promotes code reusability and makes your class more versatile.

Constructors can perform additional initialization logic beyond setting fields. For example, they can acquire resources, open files, connect to databases, or perform other setup tasks. The default constructor may not be suitable for these scenarios, so custom constructors are needed.

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

In Java, parametrized constructors and their advantages?

A

Parametrized constructors allow you to initialize object instances with different values, providing flexibility in how objects are created. This flexibility is especially useful when you need to create objects with various initial states.

Parametrized constructors accept one or more parameters (arguments) that are used to initialize the instance variables of the object. These parameters are specified in the constructor’s parameter list.

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

Constructor chaining and why?

A

Constructor chaining in Java is a technique that allows you to call one constructor from another within the same class or from a subclass constructor.

for example we want to create a car object with 5 different values (year, model, etc) you ensure that every Car object is initialized with some reasonable default values, even if the user does not specify them. This guarantees that you don’t have uninitialized or partially initialized objects.

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

Is constructor overriding allowed?

A

constructors cannot be overridden in the same way that methods can be overridden. Overriding a method means providing a different implementation of the method in a subclass, while maintaining the same method signature (name, return type, and parameters). However, constructors do not have a return type and are not inherited by subclasses.

Instead, when you create a subclass, you can invoke the constructor of the superclass using the super keyword and provide additional functionality specific to the subclass.

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

What is the purpose of the “this” keyword in a constructor?

A

this keyword is used in a constructor to differentiate between instance variables (fields) of the class and parameters or local variables with the same name. Its primary purpose is to resolve naming conflicts and clarify which variable you are referring to within the constructor’s scope.

19
Q

How do you create an object of a class that has multiple constructors?

A

When a class has multiple constructors (constructor overloading), you can create an object of that class by choosing which constructor to call based on the specific initialization requirements you have. To create an object of such a class, you use the new keyword followed by the constructor you want to invoke.

20
Q

What happens when you attempt to return a value from a constructor?

A

Attempting to return a value explicitly from a constructor using the return keyword is a compilation error. Constructors are responsible for initializing the object’s state and do not return values like regular methods. Instead, they implicitly return a reference to the newly created object.

21
Q

Explain the concept of a copy constructor in Java.

A

a copy constructor is a constructor that takes an object of the same class as its argument and creates a new object that is a copy of the provided object. The purpose of a copy constructor is to create a new object with the same state as an existing object, typically by copying the values of instance variables from the source object to the newly created object.

public Person(Person otherPerson) {
this.name = otherPerson.name;
this.age = otherPerson.age;
}

22
Q

Can you inherit constructors from a superclass in Java?

A

constructors are not inherited from a superclass to its subclasses. Each class, including a subclass, must define its own constructors. However, there is a mechanism called constructor chaining, where a subclass constructor can call a constructor from its superclass using the super keyword. This allows you to reuse and extend the initialization logic of the superclass constructors.

23
Q

What are getters and setters in Java, and why are they used?

A

Getters and setters are methods used in Java classes to access and modify the private fields (instance variables) of an object. Getters provide access (reading) to the values of these fields, while setters allow for modification (writing) of these values. They are used to control access to the fields and encapsulate the internal state of an object, providing better data encapsulation, validation, and flexibility.

24
Q

Explain the naming convention for getters and setters in Java.

A

Getters typically follow the naming convention getPropertyName() or isPropertyName() for boolean properties. Setters follow the naming convention setPropertyName(). Here, PropertyName represents the name of the field being accessed or modified.

25
Q

Why are getter and setter methods typically declared as public in Java?

A

Getter and setter methods are often declared as public to allow controlled access and modification of private fields from outside the class while maintaining encapsulation. This way, you can provide controlled access to the object’s state without exposing the fields directly.

26
Q

What is the benefit of making instance variables private and providing public getters and setters?

A

By making instance variables private and providing public getters and setters, you achieve data encapsulation. This ensures that the object’s state cannot be directly modified without proper validation and control, promoting data integrity and making it easier to implement future changes or validations.

27
Q

What is the role of the this keyword in getter and setter methods?

A

The this keyword in getter and setter methods is used to refer to the current instance of the class. It allows you to distinguish between instance variables (fields) and parameters or local variables that may have the same names. By using this, you can explicitly specify that you are referring to the instance variable and not a local variable or parameter.

28
Q

Can you have static getter and setter methods in Java classes? What are their use cases?

A

Yes, you can have static getter and setter methods in Java classes. Static getter and setter methods are associated with the class itself, rather than with individual instances of the class. They are used to get or set static (class-level) variables or to provide controlled access to such variables. Use cases include managing configuration settings, counters, or other shared data across instances of a class.

29
Q

What is the purpose of using final with getter or setter methods?

A

Using final with getter or setter methods means that the methods cannot be overridden in subclasses. This is useful when you want to ensure that the behavior of these methods remains consistent and cannot be modified by subclasses. It’s often used to provide a level of method immutability in a class’s interface.

30
Q

Enums

A

Enums (short for “enumerations”) in Java are a special data type that allow you to define a fixed set of named constants. Enumerations are used to represent a group of related constants, and they offer several features and benefits in Java:

Fixed Set of Values: Enums define a fixed set of values, which are essentially named constants. These values are typically mutually exclusive and represent all possible states or options for a particular concept.

Readability and Self-Documenting Code: Enum constants have meaningful names, making your code more readable and self-documenting. Instead of using integer or string literals, you can use enum constants with descriptive names.

31
Q

what is nested classes and what types?

A

Nested classes, also known as inner classes in Java, are classes defined within another class. These inner classes have certain features and use cases that make them a powerful tool for organizing and encapsulating code in Java. There are four types of nested classes in Java:

Static nested classes

Non-static nested classes

Local classes

Anonymous inner classes

32
Q

Static nested classes

A

These are static classes defined within another class. They are essentially regular top-level classes but are nested for packaging convenience. They can’t access non-static members of the outer class directly.

33
Q

Non-Static Nested Classes (Inner Classes)

A

These are inner classes defined without the static keyword within another class. They have access to the members (including private) of the outer class and can be seen as an extension of the outer class.

34
Q

Local Classes

A

Local classes are defined within a block of code, typically within a method. They can access the members of the outer class, as well as local variables that are effectively final (not modified after initialization).

35
Q

What is a SOLID OOPS Principle?

A

SOLID is one of the most popular sets of design principles in object-oriented software development. It’s a mnemonic acronym for the following five design principles:

Single Responsibility Principle (SRP)
Open/Closed Principle (OCP)
Liskov Substitution Principle (LSP)
Interface Segregation Principle (ISP)
Dependency Inversion Principle (DIP)

36
Q

What is the Single Responsibility Principle?

A

A class should have only one reason to change.
It suggests that a class should have one and only one responsibility or job.
This principle promotes high cohesion and reduces coupling by ensuring that each class is responsible for only one aspect of the system.

37
Q

What is the Open Closed Principle?

A

Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
This means that you should be able to extend the behavior of a module without modifying its source code.
It encourages the use of abstraction, inheritance, and polymorphism to achieve flexibility and scalability.

38
Q

What is the Liskov Substitution Principle?

A

Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program.
In other words, derived classes must be substitutable for their base classes without altering the desirable properties of the program.
This principle ensures that the behavior of derived classes remains consistent with that of the base class.

39
Q

What is the Interface Segregation Principle?

A

Clients should not be forced to depend on interfaces they do not use.
It suggests that large interfaces should be broken down into smaller and more specific ones so that clients only need to know about the methods that are relevant to them.
This principle helps in achieving loose coupling and prevents interface pollution.

40
Q

What is the Dependency Inversion Principle?

A

High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
It promotes decoupling between modules by relying on abstractions rather than concrete implementations.
This principle facilitates easier maintenance, testing, and scalability of the system.

41
Q

What are All the Different Ways to Create an Object in Java?

A

In Java, there are several ways to create objects:

  1. Using the new keyword: The most common way to create an object is by using the new keyword followed by a constructor. For example:
    java
    MyClass obj = new MyClass();
  2. Using Class.forName(): You can create an object using the Class.forName() method, which dynamically loads and initializes a class. For example:
    java
    MyClass obj = (MyClass) Class.forName("MyClass").newInstance();
  3. Using Object.clone(): If a class implements the Cloneable interface, you can create a copy of an existing object using the clone() method. For example:
    java
    MyClass obj1 = new MyClass();
    MyClass obj2 = (MyClass) obj1.clone();
  4. Using Object Deserialization: You can create an object by deserializing it from a byte stream using object deserialization. For example:
    java
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.ser"));
    MyClass obj = (MyClass) in.readObject();
  5. Using newInstance() method: For classes that have a public no-argument constructor, you can use the newInstance() method of the Class class to create an instance dynamically. For example:
    java
    MyClass obj = MyClass.class.newInstance();

These are some of the common ways to create objects in Java, each with its own use case and applicability.

42
Q

Is Java a pure object-oriented programming language?

A

There are a lot of arguments around whether Java is purely object-oriented or not. Well, Java is not a pure OOP language due to two reasons:

The first reason is that the Object-oriented programming language should only have objects whereas Java contains 8 primitive data types char, boolean, byte, short, int, long, float, and double which are not objects. These primitive data types can be used without the use of any object.

In Java, the presence of the static keyword allows for the creation of static variables and methods, which can be accessed without the need to instantiate objects. This feature deviates from the purely object-oriented paradigm where all interactions occur through message passing between objects. In a pure object-oriented language, we should access everything by message passing (through objects). But Java contains static variables and methods that can be accessed directly without using objects.

Message passing is a fundamental concept in object-oriented programming (OOP) where objects communicate with each other by sending and receiving messages. In OOP, objects are the building blocks of a program, and they encapsulate both data (attributes) and behavior (methods). Objects interact with each other by sending messages, which are requests for action or information.

43
Q
A
myname = damiane