Object oriented programming - jyotiprasadpal/useful-resources GitHub Wiki

What are the different techniques of reusing code? You have below inheritance. Goldfish is new type and it can only swim. How to solve this problem?

Animal | eat(),walk() -------------- GoldFish Person Dog swim()

You've engine, tyre, door class. Use them to design car type.

[Hint: use dependency injection]

You've a table fan and a ceiling fan. How do you model it using OOP principles.

You can't instantiate abstract classes. Can you call abstract class constructor? When?

Give an example where LSP is violated.

https://softwareengineering.stackexchange.com/questions/170138/is-this-a-violation-of-the-liskov-substitution-principle
https://stackoverflow.com/questions/43878518/solid-principle-lsp-violation

What are the differences between procedure-oriented languages and object-oriented languages?

Procedure Oriented Language: PO Language is fully concentrates on Procedures/functions/methods. It normally works as a sequence of actions as seen in flowchart or in any algorithm. It follows top-down approach. It totally focuses on methods and not the data which is utilized by methods. In PO languages if data is used by many methods then its declared as global data but there is a problem if we do that, what is that, if we forgot or by mistake if we consume that data in some other method than it comes with problem. Mostly these scenarios happen in large systems.

Example: COBOL, PASCAL, C, FORTRAN etc.

Object Oriented Language: OO concepts says it thinks about data and binds that data and methods those are manipulating that data into one entity known as object and then utilize that object into system. It uses bottom up approach.

Example: C++, Java, C#, VB.Net etc.

There are some fundamental concepts of OO Language which a language has to follow to be a truly OO language.

  • OBJECT
  • CLASS
  • ABSTRACTION
  • ENCAPSULATION
  • DATA HIDING / INFORMATION HIDING
  • INHERITANCE
  • POLYMORPHISM

List features of object oriented programming.

Object oriented programming features: Follows bottom up approach. Emphasis is on data. Programs are divided into objects. Functions and data are bound together. Communication is done through objects. Data is hidden.

List features of procedure oriented programming.

Procedure oriented programming features: Follows top down approach. Emphasis is on procedure. Programs are divided into functions. Data moves around freely.

What is Object Oriented programming?

According to Wikipedia, Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. Programming techniques may include features such as abstraction, encapsulation, inheritance, and polymorphism.

Explain basic features of Object Oriented Programming.

Abstraction _Abstraction is a process of identifying the relevant qualities and behaviors an object should possess. _ Let’s take an example to understand abstraction. A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, USB ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works. You just need to know how to operate the laptop by switching it on. The intrinsic details are invisible. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone. So here the Laptop is an object that is designed to hide its complexity.

Think if you need to write a piece of software to track the student’s details of a school, you may probably need to create Students objects. People comes in all different backgrounds, educational qualifications, locations, hobbies, ages and have multiple religion, language but in terms of application, an student is just a name, age, class and roll number, while the other qualities are not relevant to the application. Determining what other qualities (background, qualifications, location, hobbies etc) are in terms of this application is abstraction. In object-oriented software, complexity is managed by using abstraction. Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details. A well thought-out abstraction is usually simple, and easy to use in the perspective of the user, the person who is using your object.

Encapsulation Encapsulation is a method for protecting data from unwanted access or alteration by packaging it in an object where it is only accessible through the object's interface. Encapsulation is often referred to as information hiding. But both are different. In fact information hiding is actually the result of Encapsulation. Encapsulation makes it possible to separate an object's implementation from its original behavior - to restrict access of its internal data. This restriction facilitates certain details of an object’s behavior to be hidden. This allows to protect an object's internal state from corruption by its user. It is the mechanism by which Abstraction is implemented. In other words you can say that it is the result of the Encapsulation. For example, the Laptop is an object that encapsulates many technologies/hardware that might not be understood clearly by most people who use it.

Encapsulation is the ability of an object to hide its data and methods from the rest of world. It is one of the fundamental principles of OOPs. Say we create a class, named Calculations. This class may contain a few members in form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, members of the class are not exposed to the outer world directly, rather, they encapsulated by the class.

encapsulation

Inheritance Inheritance is the ability to define a new class or object that inherits the behavior and its functionality of an existing class. The new class or object is called a child or subclass or derived class while the original class is called parent or base class. For example, in a software company Software Engineers, Sr. Software Engineers, Module Lead, Technical Lead, Project Lead, Project Manager, Program Manager, Directors all are the employees of the company but their work, perks, roles, responsibilities differs. So in OOP, the Employee base class would provide the common behaviors of all types/level of employee and also some behaviors properties that all employee must have for that company. The particular sub class or child class of the employee would implement behaviors specific to that level of the employee. So by above example you can notice that the main concept behind inheritance are extensibility and code reuse (in this case you are extending the Employee class and using its code into sub class or derived class). Polymorphism As name suggests, Polymorphism means an ability to assume different forms at different places. In OOP, it is a language's ability to handle objects differently based on their runtime type and use. Polymorphism is briefly described as "one interface, many implementations". Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism.

  1. Compile time polymorphism - It is achieved by overloading functions and operators
  2. Run time polymorphism - It is achieved by overriding virtual functions Let’s say you have a class that have many Load methods having different parameters, this is called Compile time polymorphism. Let’s take another example where you have a virtual method in the base class called Load with one parameter and you have redefined its functionality in your sub class by overriding base class Load method, this is called Run time polymorphism.

State some of the advantages of object oriented programming?

Some of the advantages of object oriented programming are as follows: -

  1. A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface.
  2. Ease of maintenance and modification to the existing objects can be done with ease.
  3. A good framework is provided which facilitates in creating rich GUI applications. Data hiding helps create secure programs. Redundant code can be avoided by using inheritance. Multiple instances of objects can be created. Work can be divided easily based on objects. Inheritance helps to save time and cost. Easy upgrading of systems is possible using object oriented systems. What are the problems faced by the developer using object oriented programming language? These are some of the problems faced by the developer using object oriented language they are: -
  4. Object oriented uses design patterns which can be referred to as anything in general.
  5. Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design.

What are the basic concepts of OOPs?

The following are the basic concepts of OOPs: Classes, Objects, Data abstraction and encapsulation, Polymorphism, Inheritance, Message Passing, and Dynamic Binding.

What is data encapsulation?

Wrapping up of member data and member functions together in a class is called data encapsulation.

What is data abstraction?

Data abstraction refers to the act of providing only required features and hiding all the non-essential details for usage.

Explain the abstraction and encapsulation principle.

Abstraction means hiding the internal details and just exposing the functionality. For Example:-When you change the gear of your car, you know the gears will be changed without knowing how they are functioning internally. Abstraction focuses on the outside view of an object (i.e. the interface)

Encapsulation means put the data and the function that operate on that data in a single unit(information hiding) .Encapsulation prevents clients from seeing its inside view, where the behavior of the abstraction is implemented. Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition): "Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics." In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally, _Example 1: _ In the .NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding). _Example 2: _ Encapsulation is defined as the process of wrapping up the data members and member functions together into a single unit. It is dependent on the object data type. Abstraction is the process of eliminating unnecessary details thereby highlighting the important features. It is independent of the object data type.

A real world example, consider you have setup a big building(say a company), the details regarding materials used to built (glass, bricks), type of work, manager of the company, number of floors, design of the building, cost of the building etc. can be classified as ABSTRACTION. Whereas, type of glass or bricks (grey one or red one) used, who all work for which all departments and how they work, cost of each and every element in the building, etc, comes under Data ENCAPSULATION. Abstraction-outer layout, used in terms of design Encapsulation-inner layout, used in terms of implementation.

What is the advantage of encapsulation in object oriented programming?

Encapsulation is important because it maintains object integrity. By providing only the most necessary means of data access in the interface, we can prevent unwanted changes to the object’s state through hidden, or encapsulated, methods and properties. With well defined interfaces that rarely change, user interactions and unit testing become oblivious to changes in implementation. One advantage is that with encapsulation, when using objects, the object need not reveal all its attributes and behaviors. In good Object-Oriented Design (at least what is generally accepted as good), an object should only reveal the interfaces needed to interact with it. Details not pertinent to the use of the object should be hidden from other objects. It is really the fundamental concept of Object-Oriented. Whenever the interface/implementation paradigm is covered, we are really talking encapsulation. This encapsulation pertains equally to data and behavior. Another big advantage of encapsulation is that it makes using information for unintended purposes more difficult, and this reduces logic errors.

What is the difference between encapsulation and data hiding?

There are a lot of pretty much different concepts. Three a little bit related are Info Hiding, Data Hiding and Encapsulation. With no details, you may use all terms as a synonyms, but still if you are talking about Paradigm or Concept of OOP you should clearly understand the difference. So, Data Hiding is a concept of making all the data (fields) private e.g. not accessible from the other objects, classes, APIs in the system. The only class/object/API have to know about the data and how to operate them. Private fields with accessors is a good example. As for the Info Hiding - this more about the methods. Now, you are trying to hide e.g. make private the implementation of methods, to hide the design decisions. For example, you API should return Interface Object reference but not Class Object reference and then another client API wouldn't know how you API is implemented. For example, if you are getting cash in ATM you should just type your pin a get your money and you don't really know how they are transferred to you from you balance. Finally, the Encapsulation is much more than just Data Hiding. Some folks do think this about data, some - about methods. I should say this about both. Also, I'm not in favour of talking about Hiding at all when you describe the incapsulation term. My call is that the Encapsulation is logical integration of the data and/or the function within one entity (class, object, package, library, API etc) with or without hiding them from another entities. Also, I believe that one more very important thing is that Function (operations, responsibility, scope of methods) is encapsulated the only in the case if there is now any other entity with the same (or very similar) Function in the system. And few samples to sum up. If we clearly understand all the concept than we may say three following things about our application:

  1. Library Blah encapsulate all operations (methods) needed to work with the Database.
  2. Design decisions that were made during implementation of Library Blah are hidden within the library.
  3. All the data that are transferred from/to the Database through Library Blah are hidden within appropriate Transfer Objects and accessible only through their accessors.

What are ADTs?

ADTs stand for abstract data types. Classes which provide data abstraction are referred to as ADTs.

What is inheritance?

The process of inheriting the properties of one object by another object is called inheritance.

C# supports two types of Inheritance mechanisms:

  1. Implementation Inheritance
  2. Interface Inheritance

What is Implementation Inheritance?

When a class (type) is derived from another class (type) such that it inherits all the members of the base type it is Implementation Inheritance.

What is Interface Inheritance?

When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.

In general, Classes can be derived from another class, hence support Implementation inheritance. At the same time Classes can also be derived from one or more interfaces. Hence they support Interface inheritance. Structs can derive from one more interface, hence support Interface Inheritance. Structs cannot be derived from another class they are always derived from System.ValueType.

Give example of Implicit and Explicit Interface Implementations.

As mentioned before .Net support multiple implementations, the concept of implicit and explicit implementation provide safe way to implement methods of multiple interfaces by hiding, exposing or preserving identities of each of interface methods, even when the method signatures are the same. Let's consider the interfaces defined below:

interface IDisposable
{
    void Dispose();
} 

Here you can see that the class Student has implicitly and explicitly implemented the method named Dispose() via Dispose and IDisposable.Dispose.

class Student : IDisposable  
{  
    public void Dispose()  
    {  
        Console.WriteLine("Student.Dispose");  
    }  

    void IDisposable.Dispose()  
    {  
        Console.WriteLine("IDisposable.Dispose");  
    }  
}    

What are the advantages of inheritance?

Inheritance offers the following advantages -- 1.Developement model closer to real life object model with hierarchical relationships 2.Reusability -- facility to use public methods of base class without rewriting the same 3.Extensibility -- extending the base class logic as per business logic of the derived class 4.Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class

Discuss how derived class access to base class members.

A derived class has access to the public, protected, internal, and protected internal members of a base class. Even though a derived class inherits the private members of a base class, it cannot access those members. However, all those private members are still present in the derived class and can do the same work they would do in the base class itself. For example, suppose that a protected base class method accesses a private field. That field has to be present in the derived class in order for the inherited base class method to work properly.

Why doesn't the Java language support multiple inheritance?

Whenever you find yourself asking why Java has or does not have some feature, consider the design goals behind the Java language. With that in mind, I started my search by skimming through "The Java Language Environment" by James Gosling and Henry McGilton (Sun Microsystems), a white paper published in May 1996 that explains some of the reasoning behind Java's design. As the white paper states, the Java design team strove to make Java:

  • Simple, object oriented, and familiar
  • Robust and secure
  • Architecture neutral and portable
  • High performance
  • Interpreted, threaded, and dynamic

The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple). In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritances from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritances just weren’t worth the headache. Note: For a discussion of the diamond problem, a classic multiple inheritance challenge, read Bill Venners's "Designing with Interfaces" (JavaWorld, December 1998) and Tony Sintes's "Java Diamonds Are Forever" (JavaWorld, March 2001).

Instead, Java's designers chose to allow multiple interface inheritance through the use of interfaces, an idea borrowed from Objective C's protocols. Multiple interface inheritance allows an object to inherit many different method signatures with the caveat that the inheriting object must implement those inherited methods. Multiple interface inheritance still allows an object to inherit methods and to behave polymorphically on those methods. The inheriting object just doesn't get an implementation free ride. For an excellent discussion of interface inheritance, read Wm. Paul Rogers's "Reveal the Magic Behind Subtype Polymorphism" (JavaWorld, April 2001).

Why multiple inheritances are not supported by Java/C#?

Due to the concept of overridding Java doesn't support multiple inheritance. We have the concept of Deadly Diamond of Death . i.e. As we have an overridding concept in Java. We know what overridding is where the method name including parameters return types should be same. If mutliple inheritance is provided in java. eg:
A<- B A-<C and now B C<-D
We have a method viz. display() in A we are overriding that in B and C. If D extends that two classes then if I call the display() then there will be ambiguity. To call which version of display(). As we don’t have the concept of virtual functions what we have in c++. This is the reason why we don’t have multiple inheritances in java.

When the multiple inheritance is allowed, means when a language allows the class to extend multiple classes, that leads to the ambiguity as to which class method to consider, when two of its parents have the same method signature. This is called diamond ring problem.

What are the types of Inheritance?

There are five types of inheritance.

  1. Single inheritance
  2. Multilevel inheritance
  3. Multiple inheritance
  4. Hierarchical inheritance
  5. Hybrid inheritance

We can take support for multiple inheritances also but with the help of Interface in Java/C#.

What is diamond problem/dreaded diamond in OOP languages?

In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C? For example, in the context of GUI software development, a class Button may inherit from both classes Rectangle (for appearance) and Clickable (for functionality/input handling), and classes Rectangle and Clickable both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an overridden equals method in both Rectangle and Clickable, which method should be eventually called? It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. In this article, class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.

                                          A diamond class inheritance diagram.

z = x + y; //x, y & z are ComplexNumber

But, if you don't have the operator overload for + operator what you should do to add them?? You have to repeat the implementation of the + operator several times, or put it in a method and call it several times.

Give an example of diamond problem. How can this problem be solved?

This Jurassic Park scenario potentially could be represented by the following inheritance hierarchy:

                                          Multiple inheritance in Jurassic Park

The diamond problem can arise in inheritance hierarchies like the one shown in Figure 1. In fact, the diamond problem gets its name from the diamond shape of such an inheritance hierarchy. One way the diamond problem can arise in the Jurassic Park hierarchy is if both Dinosaur and Frog, but not Frogosaur, override a method declared in Animal. Here's what the code might look like if Java supported traditional multiple inheritance:

abstract class Animal {

    abstract void talk();
}

class Frog extends Animal {

    void talk() {

        System.out.println("Ribit, ribit.");
}

class Dinosaur extends Animal {

    void talk() {
        System.out.println("Oh I'm a dinosaur and I'm OK...");
    }
}

// (This won't compile, of course, because Java
// only supports single inheritance.)
class Frogosaur extends Frog, Dinosaur {
}

The diamond problem rears its ugly head when someone tries to invoke talk() on a Frogosaur object from an Animal reference, as in:

Animal animal = new Frogosaur();
animal.talk();

Because of the ambiguity caused by the diamond problem, it isn't clear whether the runtime system should invoke Frog's or Dinosaur's implementation of talk(). Will a Frogosaur croak "Ribbit, Ribbit." or sing "Oh, I'm a dinosaur and I'm okay..."?
The diamond problem would also arise if Animal had declared a public instance variable, which Frogosaur would then have inherited from both Dinosaur and Frog. When referring to this variable in a Frogosaur object, which copy of the variable -- Frog's or Dinosaur's -- would be selected? Or, perhaps, would there be only one copy of the variable in a Frogosaur object? Solution
The best solution is to try to avoid such diamond problems. That will keep the design simple. In Java, interfaces solve all these ambiguities caused by the diamond problem. Through interfaces, Java allows multiple inheritance of interface but not of implementation. Implementation, which includes instance variables and method implementations, is always singly inherited. As a result, confusion will never arise in Java over which inherited instance variable or method implementation to use. Languages that allow only single inheritance (such as Ada, Objective-C, PHP, C#, Delphi/Free Pascal and Java) allow the multiple inheritance of interfaces (called protocols in Objective-C). Interfaces are essentially abstract base classes with all abstract methods and no data members. The problem is therefore avoided since there is always only one implementation of a specific method or property and no ambiguity arises.

Explain polymorphism in C#.

Polymorphism is one of the fundamental concepts of OOP. It allows you to invoke methods of derived class through base class reference during runtime. It has the ability for classes to provide different implementations of methods that are called through the same name. Types of Polymorphism:
There are 2 types of Polymorphism namely 1.Compile time polymorphism (or) Overloading 2.Runtime polymorphism (or) Overriding

_Compile Time Polymorphism: _ Compile time polymorphism is method and operator overloading. It is also called early binding. Method with same name but with different arguments is called method overloading.

public class A1
{
public void hello()
{ Console.WriteLine(“Hello”); }

public void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}

_Runtime Time Polymorphism: _ Runtime time polymorphism is done using inheritance and virtual/abstract functions. Method overriding is called runtime polymorphism. It is also called late binding. Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its super class. When overriding a method, you change the behavior of the method for the derived class.

public Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}

public  Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}

public static void main()
{
parent objParent = new child();
objParent.hello(); // Hello from Child
}

Explain polymorphism in C# with a simple example?

Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.

using System;
public class DrawingObject
{
              public virtual void Draw()
             {
                    Console.WriteLine("I am a drawing object.");
             }
}
public class Triangle : DrawingObject
{
             public override void Draw()
        	{
 		Console.WriteLine("I am a Triangle.");
 	}
}
public class Circle : DrawingObject
{
 	public override void Draw()
 	{
 	 	Console.WriteLine("I am a Circle.");
 	}
}
public class Rectangle : DrawingObject
 {
 	public override void Draw()
 	{
 		Console.WriteLine("I am a Rectangle.");
 	}
}
public class DrawDemo
{
 	public static void Main()
 	{
 	 	DrawingObject[] DrawObj = new DrawingObject[4];

 		DrawObj[0] = new Triangle();
 		DrawObj[1] = new Circle();
 		DrawObj[2] = new Rectangle();
 		DrawObj[3] = new DrawingObject();

 		foreach (DrawingObject drawObj in DrawObj)
 		{
 			drawObj.Draw();
 		}
 	}
}

When can a derived class override a base class member?

A derived class can override a base class member only if the base class member is declared as virtual or abstract.

What is the difference between a virtual method and an abstract method?

A virtual method must have a body where as an abstract method should not have a body.

Can fields inside a class be virtual?

No, Fields inside a class cannot be virtual. Only methods, properties, events and indexers can be virtual.

Give an example to show for hiding base class methods?

Use the new keyword to hide a base class method in the derived class as shown in the example below.

using System;
public class BaseClass
{
  	public virtual void Method()
 	{
 		Console.WriteLine("I am a base class method.");
 	}
}
public class DerivedClass : BaseClass
{
 	public new void Method()
 	{
 		Console.WriteLine("I am a child class method.");
 	}

 	public static void Main()
 	{
 		DerivedClass DC = new DerivedClass();
 		DC.Method();
 	}
}

Can you access a hidden base class method in the derived class?

Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.

using System;
public class BaseClass
{
 	public virtual void Method()
 	{
 		Console.WriteLine("I am a base class method.");
 	}
}
public class DerivedClass : BaseClass
{
 	public new void Method()
 	{
 		Console.WriteLine("I am a child class method.");
 	}

 	public static void Main()
 	{
 		DerivedClass DC = new DerivedClass();
 		((BaseClass)DC).Method();
 	}
}

What is the difference between shadow and override? or What is the difference between new and override?

The differences between the two C# keywords is due to polymorphism. When a virtual method is called on a reference, the actual type of the object to which the reference refers is used to determine which method implementation should be used. When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used. This is so even should the calling application be unaware that the object is an instance of the derived class. The following example illustrates the override keyword:

public class BaseClass
{
    public virtual void AMethod()
    {
    }
}
 
public class DerivedClass : BaseClass
{
    public override void AMethod()
    {
    }
}
 
// ...
 
BaseClass baseClass = new DerivedClass();
baseClass.AMethod();

In the preceding example, DerivedClass.AMethod will be called; because, it overrides BaseClass.AMethod. If the new keyword were used instead of the override keyword, then the method in the derived class would not override the base class method, but would hide it instead. The following is an example illustrating the new keyword:

public class BaseClass
{
    public virtual void AMethod()
    {
    }
}
 
public class DerivedClass : BaseClass
{
    public new void AMethod()
    {
    }
}
 
// ...
 
BaseClass baseClass = new DerivedClass();
baseClass.AMethod();
 
DerivedClass derivedClass = new DerivedClass();
derivedClass.AMethod();

The preceding example will call BaseClass.AMethod first, followed by DerivedClass.AMethod. Effectively, the two methods are unrelated except for the fact that they have the same name. If neither the new nor overrides keyword is specified, the result is the same as if the new were specified. However, a compiler warning will be generated to ensure that the programmer is aware that a method in the base class is being hidden.

Explain static/early binding with an example.

When a reference type variable is initialized, the reference may hold either: a) an object of the same type as that of the reference type b) an object of a type related to the reference type In the most general terms, static binding means that references are resolved at compile time. For example, Animal a = new Animal(); a.Roar(); // The compiler can resolve this method call statically.

Example 1:

public class MyClass
{
   public void DoSomething(){...}
}

public class MyOtherClass
{
   public MyOtherClass()
   {
      MyClass mc = new MyClass();
      mc.DoSomething();
   }
}

The call to DoSomething was bound statically to the instance of MyClass that we had created on the previous line. This is known at compile time, and therefore is the only thing that can happen when this code runs.

Example 2:

1                  
2                  	public class Base
3                  	{
4                  		public void Print()
5                  		{
6                  			Console.WriteLine("Base");
7                  		}
8                  	}
9                  
10              	public class Derv : Base
11              	{
12              		public void Print()
13              		{
14              			Console.WriteLine("Derv");
15              		}
16              	}
17              		

The code below is perfectly legal in this context:

1                  
2                  	Base obj;
3                  
4                  	obj = new Base();
5                  			
6                  	// This is possible since Derv is related to Base
7                  	obj = new Derv();	
8                  

In such a scenario, when a method is invoked against a reference variable, the actual method going to be called depends upon the type of the reference. For example:

1                  
2                  	Base obj;
3                  	Derv der;
4                  			
5                  	obj = new Base();
6                  	obj.Print();		// Output: 'Base'
7                  
8                  	obj = new Derv();
9                  	obj.Print();		// Output: 'Base'
10              
11              	der = new Derv();
12              	der.Print();		// Output: 'Derv'
13              

At line number 9, the compiler determines which method to call (the Base.Print method or Derv.Print method) by checking the type of the reference variable obj. Since the reference variable obj (not the actual object stored at the reference) happens to be of type Base, the compiler calls Base.Print. In a similar manner, at line number 12, the compiler invokes Derv.Print as the reference variable der is of type Derv. This is known as Static Binding because the compiler does all this at compile time while building the final IL code, which is thus static (unchangeable at run-time). Method Hiding
The type Derv derives from Base and thus inherits the Base.Print method. But note that Derv itself defines a Print method. When a derived class defines a method with the same name as that of a method in the base class, the base class’s method would never be invoked if the type of reference variable is that of the derived class. In the previous code snippet at line number 12, though Derv inherits the Base.Print method, it was Derv.Print that was invoked. Here, Derv.Print is said to be hiding Base.Print. In order to make sure that this is indeed what the developer requires, the compiler would issue a warning saying that Derv.Print is hiding Base.Print. The compiler simply wants to bring to the attention of the programmer that there exists a method with the same name in the base class, and that the derived class’s method is hiding it. To get rid of the warning, we need to use the new keyword:

1                  
2                  	public class Derv : Base
3                  	{
4                  		public new void Print()
5                  		{
6                  			Console.WriteLine("Derv");
7                  		}
8                  	}
9                  

This reassures the compiler that the programmer knows about this issue, and that this implementation is purposeful. Explain Dynamic/late binding with an example. Dynamic binding means that references are resolved at run time. For example,

public void MakeSomeNoise(object a) { 
   // Things happen... 
   ((Animal) a).Roar(); // You won't know if this works until runtime! 
} 

When you start dealing with class hierarchies and virtual methods, compiler will start using so called VTABLEs. At that time the compiler doesn't know exactly what method to call and it has to wait until runtime to figure out the right method to be invoked (this is done through VTABLE). This is called dynamic binding.

Example 1:

public abstract class WidgetBase
{
   public abstract void DoSomething();
}
public class ShinyWidget : WidgetBase
{
   public override void DoSomething()
   {
      // implementation
   }
}

public class DullWidget : WidgetBase
{
   public override void DoSomething()
   {
      // implementation
   }
}
public class MyOtherClass
{
   public void DoSomethingWithAWidget(WidgetBase widget)
   {
      widget.DoSomething();
   }
}

When someone instantiates MyOtherClass, they will call DoSomethingWithAWidget and pass in an instance of ShinyWidget or DullWidget. We have no idea which one is going to be passed in, so we can't know at compile time which implementation of DoSomething is going to be called. This is dynamic binding.

The concept of static/dynamic binding is certainly not only applicable to abstract classes. This is only one example. The same concept applies to virtual methods, in many cases.

MyNonAbstractBaseClass bc = new ImInheritedFromMNABC();
bc.VirtalMethodName();

This would use dynamic binding as well. Example 2: By using the virtual and override keywords, you could control which method is invoked in an inheritance scenario.

1                  
2                  	public class Base
3                  	{
4                  		public virtual void Print()
5                  		{
6                  			Console.WriteLine("Base");
7                  		}
8                  	}
9                  
10              	public class Derv : Base
11              	{
12              		public override void Print()
13              		{
14              			Console.WriteLine("Derv");
15              		}
16              	}
17              

This definition would yield the following result.

1                  
2                  	Base obj;
3                  			
4                  	obj = new Base();
5                  	obj.Print();		// Output: 'Base'
6                  
7                  	obj = new Derv();
8                  	obj.Print();		// Output: 'Derv'
9                  

Note that at line number 8, even though the reference variable obj was of type Base, the method that was invoked was Derv.Print rather than Base.Print. This is because of the following reasons:

  • Base.Print declares itself as virtual, which means derived classes may override this method
  • Derv.Print explicitly states that this method overrides the Base.Print method, by using the override keyword Thus, when the Print method is invoked, the derived type’s method gets invoked. In addition to Derv, there could be more types which derive from Base, or even from Derv or any of its subclasses. Consequently, at any point of time, the reference variable obj could be holding any object instance whose type is in some way related to the type Base. It is thus not possible to find out what is the actual type of the instance held in obj until runtime. Hence, binding happens at runtime when the actual object instance exists, and the method is then invoked dynamically. This is known as Dynamic Binding. Example 3: Dynamic/late Binding with hiding.
class A {
public virtual void WhoAreYou() { Console.WriteLine("I am an A"); }
}
class B : A {
public override void WhoAreYou() { Console.WriteLine("I am a B"); }
}
class C : B {
public new virtual void WhoAreYou() { Console.WriteLine("I am a C"); }
}
class D : C {
public override void WhoAreYou() { Console.WriteLine("I am a D"); }
}

C c = new D();
c.WhoAreYou();// "I am a D"
A a = new D();
a.WhoAreYou();// "I am a B" !!

What is the concept of V-Table in C#?

vtable, is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding). Suppose a program contains several classes in an inheritance hierarchy: a superclass, Cat, and two subclasses, HouseCat and Lion. Class Cat defines a virtual function named speak, so its subclasses may provide an appropriate implementation (i.e., either meow or roar). When the program calls the speak method on a Cat pointer (which can point to a Cat class, or any subclass of Cat), the run-time environment must be able to determine which implementation to call, depending on the actual type of object that is pointed to. When is a vtable created: compile time or run time? In particular, if a declare a class having one or more virtual functions, and in first case I create an object of it and in second case I don't create an object. What difference it makes in terms of number of vtable’s created?

A vtable is created in an instance of a class when the base class has one or more virtual functions. The object of the class doesn't need a vtable because this object will call it's member functions. An object subclassed off the object with virtual functions will have a vtable so that at runtime, an object of this class will use it's member function and not the base classes. Does that mean that a VTABLE is created per class, no matter their object is created or not; considering only classes having virtual functions and those derived from them. A vtable is created per object, because only at runtime will the object know if it the subclassed class or base class. This could be a lot of memory if you have 10000 objects of a class with virtual functions, but for normal data demands, you'll never have to worry about the extra memory.

Give example how virtual functions are called?

To implement virtual functions, C++ uses a special form of late binding known as the virtual table. The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner. The virtual table sometimes goes by other names, such as “vtable”, “virtual function table”, “virtual method table”, or “dispatch table”. Because knowing how the virtual table works is not necessary to use virtual functions, this section can be considered optional reading. The virtual table is actually quite simple, though it’s a little complex to describe in words. First, every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual table. This table is simply a static array that the compiler sets up at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class. Second, the compiler also adds a hidden pointer to the base class, which we will call *__vptr. *__vptr is set (automatically) when a class instance is created so that it points to the virtual table for that class. Unlike the *this pointer, which is actually a function parameter used by the compiler to resolve self-references, *__vptr is a real pointer. Consequently, it makes each class object allocated bigger by the size of one pointer. It also means that *__vptr is inherited by derived classes, which is important. By now, you’re probably confused as to how these things all fit together, so let’s take a look at a simple example:

class Base
{
public:
    virtual void function1() {};
    virtual void function2() {};
};

class D1: public Base
{
public:
    virtual void function1() {};
};

class D2: public Base
{
public:
    virtual void function2() {};
};

Because there are 3 classes here, the compiler will set up 3 virtual tables: one for Base, one for D1, and one for D2. The compiler also adds a hidden pointer to the most base class that uses virtual functions. Although the compiler does this automatically, we’ll put it in the next example just to show where it’s added:

class Base
{
public:
    FunctionPointer *__vptr;
    virtual void function1() {};
    virtual void function2() {};
};

class D1: public Base
{
public:
    virtual void function1() {};
};

class D2: public Base
{
public:
    virtual void function2() {};
};

When a class object is created, *__vptr is set to point to the virtual table for that class. For example, when a object of type Base is created, *__vptr is set to point to the virtual table for Base. When objects of type D1 or D2 are constructed, *__vptr is set to point to the virtual table for D1 or D2 respectively. Now, let’s talk about how these virtual tables are filled out. Because there are only two virtual functions here, each virtual table will have two entries (one for function1(), and one for function2()). Remember that when these virtual tables are filled out, each entry is filled out with the most-derived function an object of that class type can call. Base’s virtual table is simple. An object of type Base can only access the members of Base. Base has no access to D1 or D2 functions. Consequently, the entry for function1 points to Base::function1(), and the entry for function2 points to Base::function2(). D1’s virtual table is slightly more complex. An object of type D1 can access members of both D1 and Base. However, D1 has overridden function1(), making D1::function1() more derived than Base::function1(). Consequently, the entry for function1 points to D1::function1(). D1 hasn’t overridden function2(), so the entry for function2 will point to Base::function2(). D2’s virtual table is similar to D1, except the entry for function1 points to Base::function1(), and the entry for function2 points to D2::function2(). Here’s a picture of this graphically:

                               ![](https://github.com/jyotiprasadpal/useful-resources/raw/master/images/virtualtable.png)

Although this diagram is kind of crazy looking, it’s really quite simple: the *__vptr in each class points to the virtual table for that class. The entries in the virtual table point to the most-derived version of the function objects of that class are allowed to call. So consider what happens when we create an object of type D1:

int main()
{
    D1 cClass;
}

Because cClass is a D1 object, cClass has it’s *__vptr set to the D1 virtual table. Now, let’s set a base pointer to D1:

int main()
{
    D1 cClass;
    Base *pClass = &cClass;
}

Note that because pClass is a base pointer, it only points to the Base portion of cClass. However, also note that *__vptr is in the Base portion of the class, so pClass has access to this pointer. Finally, note that pClass->__vptr points to the D1 virtual table! Consequently, even though pClass is of type Base, it still has access to D1’s virtual table. So what happens when we try to call pClass->function1()?

int main()
{
    D1 cClass;
    Base *pClass = &cClass;
    pClass->function1();
}

First, the program recognizes that function1() is a virtual function. Second, uses pClass->__vptr to get to D1’s virtual table. Third, it looks up which version of function1() to call in D1’s virtual table. This has been set to D1::function1(). Therefore, pClass->function1() resolves to D1::function1()! Now, you might be saying, “But what if Base really pointed to a Base object instead of a D1 object. Would it still call D1::function1()?”. The answer is no.

int main()
{
    Base cClass;
    Base *pClass = &cClass;
    pClass->function1();
}

In this case, when cClass is created, __vptr points to Base’s virtual table, not D1’s virtual table. Consequently, pClass->__vptr will also be pointing to Base’s virtual table. Base’s virtual table entry for function1() points to Base::function1(). Thus, pClass->function1() resolves to Base::function1(), which is the most-derived version of function1() that a Base object should be able to call. By using these tables, the compiler and program are able to ensure function calls resolve to the appropriate virtual function, even if you’re only using a pointer or reference to a base class! Calling a virtual function is slower than calling a non-virtual function for a couple of reasons: First, we have to use the *__vptr to get to the appropriate virtual table. Second, we have to index the virtual table to find the correct function to call. Only then can we call the function. As a result, we have to do 3 operations to find the function to call, as opposed to 2 operations for a normal indirect function call, or one operation for a direct function call. However, with modern computers, this added time is usually fairly insignificant.

Give example how virtual functions are called.

A complete understanding of everything is very important in the programming world. I am taking this post to just give some explanations I know and the understanding I have with the Virtual Functions. This is an explanation given by one of the trainer who taught me C#. I'm not sure whether he has a blog or a personal website, if yes, I will definitely link him in my post. Virtual functions are normal member functions of a class, which can be over-ridden in the derived classes. The whole functionality can be replaced in the over-riding function. In C#, the virtual functions will be declared with a keyword 'virtual' and the over-riding functions will be declared with 'override' key word.
Example in C#:

using System;
namespace ConsoleApplication1
{
  class BaseClass
  {
    public BaseClass()
    {
        // TODO
    }
    virtual public void MyFunction1()
    {
        Console.WriteLine("MyFunction in Base class");
    }
    virtual public void MyFunction2()
    {
        Console.WriteLine("MyFunction in Base class");
    }
   }
 
  class DerivedClass : BaseClass
  {
    public DerivedClass()

How the call to the derived class virtual function is being made? Let me present a C++ equivalent of the above code:

class BaseClass
{
  public:
      BaseClass()
      { 
      }
    virtual public void MyFunction1()
    {
        cout<<"MyFunction1 in Base class"<<endl;
    }
    virtual public void MyFunction2()
    {
        cout<<"MyFunction2 in Base class"<<endl;
    }
};
 
class DerivedClass 
{
  public:
    DerivedClass ()
    { 
    }
    public void MyFunction()
    {
        cout<<"MyFunction in Base class"<<endl;
    }
};
void main()
{
    DerivedClass *obj;
    obj->MyFunction();    
}

I am going to explain the virtual functions with the C++ example and will give some more additional code which will explain the call semantics of the virtual functions. Whenever, there is a virtual function in the class, a v-table is constructed in the memory. The v-table has a list of addresses to the virtual functions of the class and pointers to the functions from each of the objects of the derived class. When a virtual function call is made, the v-table is used to get the addresses of the function and the function is called. Let me also explain what are the steps that executed in a constructor. Before it executes the 1st line of code in the constructor body, the following steps are performed:

  1. Base class constructer is called
  2. Call the contained object constructors
  3. Set the VPtr The step we are interested is the 3rd step - setting the VPtr. Every object has a VPtr and is stored in the 1st memory location of the object memory. VPtr will have the address of the Virtual Table which has the function addresses of all the virtual functions available. Using the Vptr we can easily access the VirtualTable of the class and make function calls as normally done with the help of function pointers. So, as you all guessed by now, the base class constructor will be called and the VPtr of the base class will be set. But, when the call returns to the derived class constructor, the derived class VPtr will be set to its own VTable address.

How to get the VPtr of the class?

long *vptr = (long *) &obj; 
// gets the vptr of the class which is stored in the 1st memory location of each object of the class 
We got the VPtr, how we need to get the address of the VTable which is also a pointer. 

long *vtable = (long *)*vptr; 
// get the vtable address 

VTable can be considered as an array of function pointers. The addresses of virtual functions declared in the class will be stored in the order they are declared. The 0th location will have the 1st virtual function's address, 1st location have the 2nd virtual function address, so on and so forth. Now we have the address of the VTable in the pointer vtable. Lets declare a function pointer.

typedef void (__stdcall *FunctionPtr)();
FunctionPtr fp = (FunctionPtr)vtable[0]; 

// pointing to MyFunction1 which is in the 0th location of the v-table We have also declared fp which is a function pointer holding a function that returns void, accepting no arguments. Let's now call the function:

fp();
fp = (FunctionPtr)vtable[1]; // pointing to 1st location which has MyFunction2
fp(); 

Now, lets talk about setting the VPtr (3rd step in a constructor - before any user written code is executed). It does set the Virtual Table address. It is just another step which is performed when ever a constructor is called. Now, lets review the below lines of code:

DerivedClass *ptr = new DerivedClass();
ptr->MyFunction1(); // calls DerivedClass MyFunction1
ptr->BaseClass::BaseClass(); 
// BaseClass constructor is called - so VPtr altered to point to BaseClass's VTable
ptr->MyFunction1(); // calls BaseClass MyFunction1   

From the comments you would have understood what is really happening. Fortunately, C# doesn't provide a way to call a base class constructor. However, you can use new operator to create a new copy of the BaseClass in this scenario to achieve the same result. Are you a person who wish to combine many steps into one (hates to waste time in typing few more lines of code or love to minimize memory utilization by reducing the no. of variables declared or confuse someone who may try to understand your code)? If you are, following is another method of calling the first virtual function of that class:

((void(*)())*(long *)*(long *)&obj)(); 

Difference between abstract class and interface

To know the difference between the two, a developer must think about abstraction and encapsulation; the two paradigm that Object Oriented Programming heavily relies on in modelling reality. Without inheritance and interfaces, we are stuck with complex trees of conditions, iterations and recursions that is probably duplicated again and again to describe a similar characteristic between two entities. This post will discuss the difference between abstract and interface, along with an (awesome!!!) example – better than you’ve seen elsewhere.

Abstract class:

  • cannot be instantiated.
  • is a special type of class in which you can have members without implementation.
  • as we know in C#/VB/Java, a class can only inherit from 1 class. This also applies for Abstract Class.
  • normally used for framework-type library classes: providing default behavior for some of its class members, but forcing the developer to implement others.
  • is believed to be faster in Java, HOWEVER I cannot find the same claim in .Net. The speed difference is probably negligible and only relevant to the most academic field.
  • the aim: making sure something is eventually implemented.
  • A class can inherit an abstract class without implementing all its abstract method. However only a class that has all its method implemented can be instantiated to an object.
  • IS-A relationship.
    e.g. Student IS A Person, Employee IS A Person.
// 'framework library' for a person
// a person can enrol and submit
// however, the class that consume this framework library
// need to provide 'where' the paperwork need to be sent
public abstract Person
{
    public abstract SendPaperWork(string paperwork)

    public void Enrol()
    {
        SendPaperWork("enrolment");
    }

    public void Submit()
    {
        SendPaperWork("report");
    }
}

// by inheriting Person abstract class
// we are enabling student to enrol and submit
// however, SendPaperWork need to be implemented
// because we need to tell it explicitly 'where'
// to send the enrolment/ submission
public class Student : Person
{
    public override SendPaperWork(string paperwork)
    {
        School.Send(paperwork);
    }
}

// an employee send the paperwork to a different 'place' than student
public class Employee : Person
{
    public override SendPaperWork(string paperwork)
    {
        Company.Send(paperwork);
    }
}

Interface:

  • cannot be instantiated.
  • is a special type of abstract class in which all the members do not have any implementations.
  • enables polymorphism. A class can implement more than 1 Interfaces.
  • normally used for application classes: providing contract for ensuring interactibility.
  • the aim: making sure something is interchangeable.
  • A class that implements an Interface need to contain all the implementation, otherwise the compiler will throw an error.
  • CAN-DO relationship.
  • e.g. Student CAN enrol, Student CAN submit assignment.
public interface ICanEnrol
{
    void Enrol();
}

public interface ICanSubmit
{
    void Submit();
}

public class Student : ICanEnrol, ICanSubmit
{
    public void Enrol()
    {
        School.Send("enrolment");
    }

    public void Submit()
    {
        School.Send("report");
    }
}

public class Employee : ICanEnrol, ICanSubmit
{
    public void Enrol()
    {
        Company.Send("enrolment");
    }

    public void Submit()
    {
        Company.Send("report");
    }
}

public class MailServer
{
    public void SendAllSubmissions()
    {
        // AllSubmitters is a collection of students and employees
        foreach (ICanSubmit submitter in AllSubmitters)
        {
            // The MailServer does not care if
            // the submitter is a student
            // or an employee, as long as it can submit
            submitter.Submit()
        }
    }
}

What is Method overloading?

Method overloading occurs when a class contains two methods with the same name, but different signatures.

What is method overloading?

Method overloading allows us to write different version of the same method in a class or derived class. Compiler automatically selects the most appropriate method based on the parameter supplied.

public class MultiplyNumbers
{
    public int Multiply(int a, int b)

    {

        return a * b;

    }

    public int Multiply(int a, int b, int c)

    {

        return a*b*c;

    }     

}

To call the above method, you can use following code.

MultiplyNumbers mn = new MultiplyNumbers();  
int number = mn.Multiply(2, 3) // result = 6  
int number1 = mn.Multiply(2, 3, 4) // result = 24  

You can't have a overload method with same number parameters but different return type. In order to create overload method, the return type must be the same and parameter type must be different or different in numbers.

What is the use/advantage of function/method overloading?

One of the key features of object-oriented programming is polymorphism. Polymorphism permits objects to behave in different ways according to the manner in which they are used. One part of polymorphism is the ability for a method to behave differently according to the types and number of parameters that are passed to it. This is achieved through method overloading. Method overloading allows the programmer to define many methods with the same name but with a different set of parameters. Each combination of parameter types is known as a signature of the method. When a call is made to one of these overloaded methods, the compiler automatically determines which of the methods should be used according to the arguments used in the call and the available method signatures. One of the greatest advantages of method overloading is the improvement that it provides to code readability and maintainability. In languages that do not support this technique, or that of optional operands, a new method must be created for every possible combination of parameters. For example, in the ANSI C programming language to truncate a value you would use trunc, truncf or truncl according to the data type being rounded. In C#, method overloading allows you to always call Math.Truncate. This becomes even more useful when a change in the requirements of the program means that data types change. Unlike with the older languages, the C# truncate method would require no code modification. When using method overloading, each version of a method should perform the same general function using different data types or numbers of parameters. Although it is possible to create two methods with the same name that perform completely different tasks, this just reduces the quality of your code. Overloading a method allows you to keep your interface consistent, and allows you to logically call the same method regardless of the types of data you are passing in. You will find that using the same name will help you remember what a procedure does, as opposed to having to come up with new names or a naming convention, to help you keep things straight.

What is operator overloading?

Operator overloading (a feature that was initially introduced in C++) is a concept that enables us to redefine the existing operators so that they can be used on user defined types like classes and structs. Declaring Operator overloading

public static <return Type> operator +(<ParamList, ...., .... >)
{
    //Implementation pf your operator
}

Why use Operator Overloading?

Operator overloading makes a program clearer than accomplishing the same operations with explicit method calls. Now if you want to add tow complex numbers of Type ComplexNumber you just need to instantiate tow objects from it then do this:
z = x + y; //x, y & z are ComplexNumber

But, if you don't have the operator overload for + operator what you should do to add them?? You have to repeat the implementation of the + operator several times, or put it in a method and call it several times.

What is operator overloading? What are the advantages of operator overloading?

It is one of the features of Object oriented programming which gives an extra ability to an operator to act on a User-defined operand(Objects). Advantages/Uses of Operator Overloading:

  • Extensability: An operator will act differently depending on the operands provided.
  • Operator is not limited to work only with primitive Data Type.
  • Makes code much more readable.

What is Method Overriding? How to override a function in C#?

Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference. C# makes use of two keywords: virtual and overrides to accomplish Method overriding. Let's understand this through small examples.

//P1.cs 
class BC
{ 
public void Display() 
{ 
System.Console.WriteLine("BC::Display"); 
}
}
class DC : BC
{ 
new public void Display() 
{ 
System.Console.WriteLine("DC::Display"); 
}
}
class Demo
{ 
public static void 
Main() 
{ 
BC b; 
b = new BC(); 
b.Display();
}
}

Output : BC::Display  

Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

In which cases you use override and new base?

Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier. What is Method Overriding? How to override a function in C#? Method overriding is a feature that allows to invoke functions (that have the same signatures) and that belong to different classes in the same hierarchy of inheritance using the base class reference. In C# it is done using keywords virtual and overrides. Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.

You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

What is a sealed class?

It is a class, which cannot be sub-classed. It is a good practice to mark your classes as sealed, if you do not intend them to be sub-classed. An error occurs if a sealed class is specified as the base class of another class. Some points to remember:

  • A class, which restricts inheritance for security reason is declared, sealed class.
  • Sealed class is the last class in the hierarchy.
  • Sealed class can be a derived class but can't be a base class.
  • A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are restricting it to inherit.

How do you prevent a class from being inherited?

Mark it as sealed.

Can you inherit from multiple base classes in C#?

No. C# does not support multiple inheritances, so you cannot inherit from more than one base class. You can however, implement multiple interfaces.

Explain the implementation phase with respect to OOP?

The design phase is followed by OOP, which is the implementation phase. OOP provides specifications for writing programs in a programming language. During the implementation phase, programming is done as per the requirements gathered during the analysis and design phases.

Give an example for object based programming language.

Ada, VB, etc are examples for object based programming language. What are the steps involved in message passing? The following are the steps involved in message passing: Creating classes, creating objects, and creating communication between objects.

Explain about message passing in object oriented programming?

Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.

What is a class?

Class is an entity which consists of member data and member functions which operate on the member data bound together. A class is a template definition of the methods and variables for a particular kind of object. In other words, class is the blue print from which individual objects are created.

What is an object?

Objects are instances of classes. Class is a collection of similar kind of objects. When a class is created it doesn’t occupy any memory, but when instances of class is created i.e., when objects are created they occupy memory space. Basically, an object is anything that is identifiable as a single material item. You can see around and find many objects like Camera, Monitor, Laptop, etc. In OOP perspective, an object is nothing but an instance of a class that contains real values instead of variables.

What is the difference between class, object and instance? Explain with real example. Is a telephone receiver set an object? If it is so, why?

In OO Programming, we often hear of terms like “Class”, “Object” and “Instance”; but what actually is a Class / Object / Instance?

In short, an object is a software bundle of related state and behavior. A class is a blueprint or prototype from which objects are created. An instance is a single and unique unit of a class. Example, we have a blueprint (class) represents student (object) with fields like name, age, course (class member). And we have 2 students here, Foo and Bob. So, Foo and Bob is 2 different instances of the class (Student class) that represent object (Student people). Let me go into details…

Object
Real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and state (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods. Telephone receiver set is an object because it has behaviors like MakeCall(), ReceiveCall(), etc and attributes like color, size, etc.

Class Class is a “template” / “blueprint” that is used to create objects. Basically, a class will consist of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.

Instance
An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the CLR will allocate a room of memory for that class instance.

How class and object are related to each other?

An object is the instantiation of the class. Class is a collection of similar kind of objects. The class must have been created before one can create an object. Each object consists of:

  • identity (e.g. name)
  • state (variables, current conditions, information/data)
  • methods (operations, actions/processes that change state)

What is an Abstract Class?

A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

When do you absolutely have to declare a class as abstract?

  1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
  2. When at least one of the methods in the class is abstract.

What is an interface class?

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

Can you inherit multiple interfaces?

Yes. .NET does support multiple interfaces.

What happens if you inherit multiple interfaces and they have conflicting method names?

It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

What is the difference between a Class and an Interface?

In .Net/ C# a class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface, an object of such class can be encapsulated inside an interface. If MyLogger is a class, which implements ILogger, there we can write ILogger log = new MyLogger();

A class and an interface are two different types (conceptually). Theoretically a class emphasis the idea of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). The two poses a clear separation from one to another. Therefore it is very difficult or rather impossible to have an effective meaningful comparison between the two, but it is very useful and also meaningful to have a comparison between an interface and an abstract class.

What’s the difference between an interface and abstract class?

In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers. Interfaces vs. Abstract Classes Feature Interface Abstract class Multiple inheritance A class may implement several interfaces. A class may extend only one abstract class. Default implementation An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden. Constants Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants. Third party convenience An interface implementation may be added to any existing third party class. A third party class must be rewritten to extend only from the abstract class. is-a vs -able or can-do Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is. Plug-in You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface. Homogeneity If all the various implementations share is the method signatures, then an interface works best. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best. Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method. Speed Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. Fast Terseness The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract. Adding functionality If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

In which Scenario you will go for Interface or Abstract Class?

The choice of whether to design your functionality as an interface or an abstract class can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes.

An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer. The answer isn't always clear-cut. Use abstract classes and interfaces in combination to optimize your design trade-offs. Here are some guidelines that might help you:

• IS-A vs. CAN-DO relationship A type can inherit only one implementation. If the derived type can't claim an IS-A relationship with the base type, don't use a base type; use an interface. Interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong with various object types, use an interface. For example, a type can convert instances of itself to another type (IConvertible), a type can serialize an instance of itself (ISerializable) , etc. Note that value types must be derived from System.ValueType, and therefore, they cannot be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship and define an interface. .NET value types can implement interfaces. Thus, primitives—such as Int32— can implement the IComparable interface, for example, making them comparable. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

Examples from FCL:
In the FCL, the classes related to streaming data use an implementation inheritance design. The System.IO.Stream class is the abstract base class. It provides a bunch of methods, such as Read and Write. Other classes—System.IO.FileStream, System.IO.MemoryStream, and System.Net.Sockets.NetworkStream—are derived from Stream. Microsoft chose an IS-A relationship between each of these three classes and the Stream class because it made implementing the concrete classes easier. For example, the derived classes need to implement only synchronous I/O operations; they inherit the ability to perform asynchronous I/O operations from the Stream base class.

Admittedly, choosing to use inheritance for the stream classes isn't entirely clear-cut; the Stream base class actually provides very little implementation. However, if you consider the Microsoft Windows Forms control classes, in which Button, CheckBox, ListBox, and all of the other controls are derived from System.Windows.Forms.Control, it's easy to imagine all of the code that Control implements, which the various control classes simply inherit to function correctly.

By contrast, Microsoft designed the FCL collections to be interface based. The System.Collections.Generic namespace defines several collection-related interfaces:
IEnumerable<T>, ICol lect ion<T>, IList<T>, and IDictionary<TKey, TValue>. Then Microsoft provided a number of classes, such as List<T>, Dictionary<TKey, TValue>, Queue<T>, Stack<T>, and so on, that implement combinations of these interfaces. Here the designers chose a CAN-DO relationship between the classes and the interfaces because the implementations of these various collection classes are radically different from one another. In other words, there isn't a lot of sharable code between a List<T>, a Dictionary<TKey, TValue>, and a Queue<T>.

  • Design flexibility and Ease of use
    If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members. In case of Abstract class we can define COMMON functionalities in super class and those can be used in the derived class where as in Interface we can’t do that. ( this i would say as advantage of abstract class). This helps to reuse code. It's generally easier for you as a developer to define a new type derived from a base type than to implement all of the methods of an interface. The base type can provide a lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members. When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility. Interfaces offer more design flexibility; precisely because, they can be implemented by any class regardless of its type hierarchy. In case of Interface the derived class can implement any number of interface but restricted to extend only one abstract class (this i would say as advantage of Interface)

Example
The System.IO.Stream class is the abstract base class. It provides a bunch of methods, such as Read and Write. Other classes—System.IO.FileStream, System.IO.MemoryStream, and System.Net.Sockets.NetworkStream—are derived from Stream. The subclasses make use of the common methods available in superclass.

  • Versioning/Adding functionality If you add a method to the base type, the derived type inherits the new method's default implementation for free. If additional functionality is needed in derived classes, it can be added to the base class without breaking code. This simplifies versioning. An abstract class can be extended by adding new non-abstract methods with default implementations. Also, a convenience method is easily added to an abstract class.

In fact, the user's source code doesn't even have to be recompiled. Adding a new member to an interface forces the inheritor of the interface to change its source code and recompile. This means that an interface cannot be modified without breaking its contract with the classes which implement it. Once an interface has been shipped, its member set is permanently fixed. An API based on interfaces can only be extended by adding new interfaces. If interfaces are poorly designed and have to change or not easy to implement we will not receive the benefits of using them and all they achieve is to make our code more complex. We need to think out the interfaces very carefully at design time before getting too far into the implementation because once they are implemented and made available to other resources they should not change.

If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

Example
If we consider interface IDisposable from FCL, it has Dispose() method. The client of this interface implements this interface in .NET 2.0. Now, in case, it is thought to provide extra capabilities to this interface in future versions of .NET. If a new member is introduced, the existing client code implementing this interface would fail. The client code has to implement all members of this changed interface. This also requires code to be recompiled. The solution to this problem would be to create a new interface say IDisposable_v2.

IDisposable_v2: IDisposable
{
//new member
}

This would ensure that existing client code does not break. But this kind of solution is difficult to maintain with multiple versions of interface. This is a drawback with interface design. Extra care should be taken while designing interface to ensure interface is not changed in future. If there is a small chance that interface would be required to be changed, go with abstract class.

  • Consistent implementation No matter how well an interface contract is documented, it's very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM suffers from this very problem, which is why some COM objects work correctly only with Microsoft Office Word or with Microsoft Internet Explorer. By providing a base type with a good default implementation, you start off using a type that works and is well tested; you can then modify parts that need modification.

Can we create a Java/C# class inside an interface?

Yes, classes can be declared inside interfaces. This technique is sometimes used where the class is a constant type, return value or method argument in the interface. When a class is closely associated with the use of an interface it is convenient to declare it in the same compilation unit. This proximity also helps ensure that implementation changes to either are mutually compatible. A class defined inside an interface is implicitly public static and operates as a top level class. The static modifier does not have the same effect on a nested class as it does with class variables and methods. The example below shows the definition of a StoreProcessor interface with nested StorageUnit class which is used in the two interface methods.

Can an interface extend an abstract class?

In Java/C# an interface cannot extend an abstract class. An interface may only extend a super-interface. And an abstract class may implement an interface. It may help to think of interfaces and classes as separate lines of inheritance that only come together when a class implements an interface, the relationship cannot be reversed.

What is Marker Interface in .Net? How can I implement in Dot Net? What is the exact use of this? If possible please explain with an example.

Marker interfaces as the name suggests, doesn’t have anything in it, just used to mark a class.

If you have worked with asp.net, you might have used IRequiredSessionState. This has no member, just acts as a Marker interface.

In .NET we use Marker Interface using Attributes.

Is it recommended to use Marker Interface? CONSIDER defining an interface if you need to support its functionality on types that already inherit from some other type. AVOID using marker interfaces (interfaces with no members). If you need to mark a class as having a specific characteristic (marker), in general, use a custom attribute rather than an interface.

// Avoid
public interface IImmutable {} // empty interface
public class Key: IImmutable {
   ...
}
//Do
[Immutable]
public class Key {
   ...
}

Methods can be implemented to reject parameters that are not marked with a specific attribute as follows:

public void Add(Key key, object value){
  if(!key.GetType().IsDefined(typeof(ImmutableAttribute), false)){
    throw new ArgumentException("The parameter must be immutable","key");
  } 
}
RICO MARIANI 

Of course any kind of marking like this has a cost. Attribute testing is a lot more costly than type checking. You might find that it's necessary to use the marker interface approach for performance reasons—measure and see. My own experience is that true markers (with no members) don't come up very often. Most of the time, you need a no- kidding-around interface with actual functionality to do the job, in which case there is no choice to make. The problem with this approach is that the check for the custom attribute can occur only at runtime. Sometimes, it is very important that the check for the marker be done at compile-time. For example, a method that can serialize objects of any type might be more concerned with verifying the presence of the marker than with type verification at compile-time. Using marker interfaces might be acceptable in such situations. The following example illustrates this design approach:

public interface ITextSerializable {} // empty interface
public void Serialize(ITextSerializable item){
   // use reflection to serialize all public properties
   ...
}

DO provide at least one type that is an implementation of an interface.

This helps to validate the design of the interface. For example, System.Collections.ArrayList is an implementation of the System.Collections.IList interface. DO provide at least one API consuming each interface you define (a method taking the interface as a parameter or a property typed as the interface). This helps to validate the interface design. For example, List<T>.Sort consumes IComparer<T> interface. DO NOT add members to an interface that has previously shipped. Doing so would break implementations of the interface. You should create a new interface to avoid versioning problems. Except for the situations described in these guidelines, you should, in general, choose classes rather than interfaces in designing managed code reusable libraries.

How we can use a class defined inside an interface? or Why we define a class inside an interface?

A class is defined inside an interface to bind the interface to a TYPE. A small but nonsense example:

interface employee{ 
    class Role{ 
          public String rollname; 
          public int Role id; 
          public Object person; 
     } 
    Role getRole(); 
    // other methods 
} 

In the above interface you are binding the Role type strongly to the employee interface (employee.Role). Another usage than those linked by Eric P: defining a default/no-op implementation of the interface.

interface IEmployee 
{ 
 
    void workHard ();   
    void procrastinate (); 
 
    class DefaultEmployee implements IEmployee  
    { 
        void workHard () { procrastinate(); }; 
        void procrastinate () {}; 
    } 
 
} 

Yet, another sample — implementation of Null Object Pattern:

interface IFoo 
{ 
    void doFoo(); 
    IFoo NULL_FOO = new NullFoo(); 
 
    final class NullFoo implements IFoo 
    { 
        public void doFoo () {}; 
        private NullFoo ()      {}; 
    } 
} 
  
... 
IFoo foo = IFoo.NULL_FOO; 
... 
bar.addFooListener (foo); 
... 

Which of the following are true about the class defined inside an interface

  1. it is not possible in the java Laungage.
  2. The class is always public.
  3. The class is always static.
  4. the class methods cannot call the methods declared in the interface.
  5. the class methods can call only the static methods declared in the interface.

You should know this first regarding nested classes in an interface:

You can put the definition of a class inside the definition of an interface. The calss will be an inner class to the interface. An inner class to an interface will be static and public by default. The code structure would be like this :

interface Port {   
//Methods & constants declared in the interface...   
class Info {   
//Definition of the class...   
}   
}  

This declares the interface Port with an inner class Info. Objects of the inner class would be of type Port.Info. You might create one with a statement like this:

Port.Info info = new Port.Info();

A class that implements the interface would have no direct connection with the inner class to the interface- it would just need to implements the methods declared by the interface, but it is highly likely it would make use of objects of the inner class.

On behalf of above description: Answer 2,3,4 are correct. 5 is incorrect because interface methods can't be static.

List the areas of applications of object oriented programming?

The following are few areas of applications of object oriented programming:

  • CAD/CAM systems
  • Office automation and decision support systems
  • Object oriented databases
  • Real time systems
  • Simulation and modeling.

How does a class provide data hiding?

Data hiding is provided by a class by the use of visibility label private which allows only the member functions to access the data declared as private. What does member functions represent? Member functions of a class represent the behavior of a class.

Can we call a base class method without creating instance? Yep. But ..

  • Its possible If its a static method.
  • Its possible by inheriting from that class also.
  • Its possible from derived classes using base keyword.

Default Access modifiers in C#?

An enum has default modifier as public

A class has default modifiers as private. It can declare members (methods etc) with following access modifiers:

  • public
  • protected
  • internal
  • private
  • protected internal

An interface has default modifier as public

A struct has default modifier as private and it can declare its members (methods etc) with following access modifiers: public, internal , private

What is Protected Internal access modifier in C#?

Protected Internal is a access modifiers for the members (methods or functions) ie. you can't declare a class as protected internal explicitly. The members access is limited to the current assembly or types derived from the containing class.

Protected Internal means the method is accessible by anything that can access the protected method UNION with anything that can access the internal method.

What is Internal access modifier in C#?

The internal keyword is an access modifier for types and type members ie. we can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll). In other words, access is limited exclusively to classes defined within the current project assembly.

For more details see http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.71).aspx

What is Private access modifier in C#?

The private keyword is a member access modifier ie. we can't explicitly declare a class as Private, however if do not specify any access modifier to the class, its scope will be assumed as Private. Private access is the least permissive access level of all access modifiers.

Private members are accessible only within the body of the class or the struct in which they are declared. This is the default access modifier for the class declaration.

What is Public access modifier in C#?

The public keyword is an access modifier for types and type members ie. we can declare a class or its member (functions or methods) as Public. There are no restrictions on accessing public members.

What is Protected access modifier in C#?

The protected keyword is a member access modifier. It can only be used in a declaring a function or method not in the class ie. a class can't be declared as protected class.

A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declare this member. In other words access is limited to within the class definition and any class that inherits from the class

A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.

Can we specify the access modifier for explicitly implemented interface method?

No, we can't specify the access modifier for the explicitly implemented interface method. By default its scope will be internal.

What is pure virtual function?

When you define only function prototype in a base class without and do the complete implementation in derived class. This base class is called abstract class and client won’t able to instantiate an object using this base class.

A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0" syntax:

class Base { 
public: 
void f1(); // not virtual 
virtual void f2(); // virtual, not pure 
virtual void f3() = 0; // pure virtual 
}; 

What is an Interface?

An interface is a contract & defines the requisite behavior of generalization of types.

An interface mandates a set of behavior, but not the implementation. Interface must be inherited. We can't create an instance of an interface.

An interface is an array of related function that must be implemented in derived type. Members of an interface are implicitly public & abstract.

An interface can inherit from another interface.

What is sealed modifiers?

Sealed types cannot be inherited & are concrete. Sealed modifiers can also be applied to instance methods, properties, events & indexes. It can't be applied to static members.

Sealed members are allowed in sealed and non-sealed classes.

What is Abstract Class?

Abstract class exists extensively for inheritance. We can't create an instance of an abstract class. Abstract type must be inherited.

Static, Value Types & interface doesn't support abstract modifiers.

Static members cannot be abstract. Classes with abstract member must also be abstract.

Can Struct be inherited?

No, Struct can't be inherited as this is implicitly sealed.

What is Virtual method?

Virtual Method has implementation & provide the derived class with the option to override it.

What is Abstract method?

Abstract method doesn't ? The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified.

Explain about the Design Phase?

In the design phase, the developers of the system document their understanding of the system. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships. The Object-Oriented Paradigm provide the implementation & forces the derived class to override the method.

Explain about the analysis phase

Describe the basic approach used in functional decomposition.

Functional decomposition is the approach to analysis that breaks down (decomposes) a problem into its functional parts without too much concern for global requirements and future modifications.

What are three reasons that cause requirements to change?

The user's understanding of what they need and what is possible grows and changes as they discuss the problem with analysts. The developer's understanding of what is possible and what is needed evolves as they become familiar with the domain and with the software. The technical environment evolves, forcing changes in how to implement. I advocate thinking about responsibilities rather than functions. What is meant by this? Give an example. Rather than thinking first about how something is done (functions), the analyst should focus on what the routine is responsible for doing - how it does it does not matter. The control program is much simpler in this case. Define "coupling" and "cohesion". What is "tight" coupling? Cohesion is how strongly the internal operations of a routine are related to each other. Coupling is how strongly a routine is dependent upon other routines.

A class is a complete definition of the behavior of an object. What three aspects of an object does it describe?

The three elements of a class are: the data elements, the methods, the interfaces (ways that data and methods can be accessed). (p. 17)

Define encapsulation. Give one example of encapsulation of behavior.

Any kind of hiding. Both data and behavior may be encapsulated. (p. 21)

What are the three perspectives for looking at objects?

Conceptual: the high-level concepts in a system (concepts, not software). At the conceptual level, an object is a set of responsibilities. Specification: the interfaces between things in the software (software, not code). At the specification level, an object is a set of methods. Implementation: how an individual routine works (code). At the implementation level, an object is code and data. (p. 13, 15-16) Interpretations

Sometimes, programmers use "modules" to isolate portions of code. Is this an effective way to deal with changes in requirements? Why or why not?

Changes to one function or routine can have impacts on other routines. Usually, routines are not independent (p. 10).

It is too limited to define an abstract class as a class that does not get instantiated. Why is this definition too limited? What is a better (or at least alternative) way to think about abstract classes?

It is too limited because it only talks in terms of its implementation: what the abstract class does and how it is treated as software. It does not describe why I would want to use an abstract class: the motivation for it and how to think about it. It ignores the "conceptual perspective" of objects that analysts need to keep in mind as they work with users to understand problems. At the conceptual level, an abstract class is a placeholder for a set of classes. It gives a way to assign a name or label to a set of classes so that I can interact with them as a whole without getting trapped by the details. (p. 19)

How does encapsulation of behavior help to limit the impact of changes in requirements? How does it save programmers from unintended side effects?

It makes the control program much less complicated since it does not have to be responsible for as much. It limits the impact that changes to the internals of an object can have on the rest of the application. (p. 24)

How do interfaces help to protect objects from changes that are made to other objects?

Interfaces define the only ways that those external objects can communicate with the object. It protects me from side effects because I know what is coming into the system. A classroom is used to describe objects in a system. Describe this classroom from the conceptual perspective. The classroom contains students who are responsible for their own behaviors: how to move from here to there, how to go from class to class. It contains a teacher who tells students where to go. Opinions and Applications

Changing requirements is one of the greatest challenges faced by systems developers. Give one example from your own experience where this has been true.

There is a fundamental weakness in functional decomposition when it comes to changes in requirements. Do you agree? Why or why not?

What do you think is the best way to deal with changing requirements?