Search code examples
language-agnosticoopprogramming-languages

Language Agnostic Basic Programming Question


This is very basic question from programming point of view but as I am in learning phase, I thought I would better ask this question rather than having a misunderstanding or narrow knowledge about the topic.

So do excuse me if somehow I mess it up.

Question:

Let's say I have class A,B,C and D now class A has some piece of code which I need to have in class B,C and D so I am extending class A in class B, class C, and class D

Now how can I access the function of class A in other classes, do I need to create an object of class A and than access the function of class A or as am extending A in other classes than I can internally call the function using this parameter.

If possible I would really appreciate if someone can explain this concept with code sample explaining how the logic flows.

Note

Example in Java, PHP and .Net would be appreciated.


Solution

  • Let's forget about C and D because they are the same as B. If class B extends class A, then objects of type B are also objects of type A. Whenever you create an object of type B you are also creating an object of type A. It should have access to all of the methods and data in A (except those marked as private, if your language supports access modifiers) and they can be referred to directly. If B overrides some functionality of A, then usually the language provides a facility to call the base class implementation (base.Foo() or some such).

    Inheritance Example: C#

    public class A
    {
         public void Foo() { } 
         public virtual void Baz() { }
    }
    
    public class B : A  // B extends A
    {
          public void Bar()
          {
              this.Foo();  // Foo comes from A
          }
    
          public override void Baz() // a new Baz
          {
              base.Baz();  // A's Baz
              this.Bar();  // more stuff
          }
    }
    

    If, on the other hand, you have used composition instead of inheritance and B contains an instance of A as a class variable, then you would need to create an object of A and reference it's (public) functionality through that instance.

    Composition Example: C#

     public class B // use A from above
     {
         private A MyA { get; set; }
    
         public B()
         {
             this.MyA = new A();
         }
    
         public void Bar()
         {
             this.MyA.Foo();  // call MyA's Foo()
         }
     }