Govt. Exams
Entrance Exams
Encapsulation is the principle of bundling data and methods together while hiding internal details. Using private fields with public properties (getters/setters) allows controlled access to the stock level, preventing unauthorized direct modifications. This is the standard practice in inventory systems.
Interfaces establish a contract that forces implementing classes to provide their own logic for calculating delivery costs, promoting code consistency without duplicating implementation.
An abstract class is ideal when you want to provide common functionality and properties to derived classes while preventing direct instantiation. It can have both abstract and concrete members.
Composition is represented by having an object of one class as a member variable of another class, allowing code reuse through object containment rather than inheritance.
class Animal { }
class Dog : Animal { }
Dog dog = new Animal(); // Line 1
You cannot assign a base class instance to a derived class reference without explicit casting. This violates type safety rules in C#.
The 'sealed' keyword prevents a class from being used as a base class for inheritance, ensuring that derived classes cannot override the sealed class.
class Base { public virtual void Display() { Console.WriteLine("Base"); } }
class Derived : Base { public override void Display() { Console.WriteLine("Derived"); } }
Base obj = new Derived();
obj.Display();
Due to polymorphism and method overriding, the Derived class's Display() method is called even though the reference type is Base. This demonstrates runtime polymorphism.
Abstract classes can have properties, fields, concrete methods, and abstract members. The statement that they cannot have properties is incorrect.
This design enables polymorphism, allowing different employee types to calculate salaries differently while using the same interface, improving maintainability.
C# automatically calls the parameterless constructor of the base class if no explicit base() call is made, ensuring base class initialization.