Solved

Inheritance in C#...

Posted on 2009-06-30
18
885 Views
Last Modified: 2012-06-21
I've created these traffic lights that cycle through in the normal fashion.

I now need to find a way of inheriting the light state strings ("Stop", "Go" etc) in a new class that cycles through the traffic light states in reverse but am stuck on how this would be done in C# 2008 Express Edition.

My two main questions then, are, how do I inherit the light states for use in a new class and would I simply use an i-- in place of the i++ in the first class for the reversing of the light cycle?

My OO experience is very limited so the answer is not obvious to me.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;
 
 

namespace Traffic_Lights

{
 

        class traffic_light

        {

            static void Main(string[] args)
 

            {

                String input = String.Empty;
 

                Console.WriteLine("Normally Cycling Traffic Lights");

               

                string[] light_state = new string[4];
 

                light_state[0] = "Stop";

                light_state[1] = "Prepare To Go";

                light_state[2] = "Go";

                light_state[3] = "Prepare To Stop";

            

 {
 

     do

         for (int i = 0; i < light_state.Length; i--)

         {
 

             input = Console.ReadLine();

             Console.WriteLine(light_state[i]);
 

         }

     while (input != "e");

                }

        }

    }

    }
 

class reverse_cycling_traffic_light 

{ 
 

// NEED TO INHERIT THE traffic_light CLASS' STATES WITHIN THIS CLASS AND USE THESE STATES WHEN DISPLAYING THE REVERSE TRAFFIC LIGHTS STATES IN THIS DIFFERENT VERSION OF THE TRAFFIC LIGHT.
 

}

Open in new window

0
Comment
Question by:glynn19872000
  • 7
  • 6
  • 4
  • +1
18 Comments
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
I'm not convinced that your inheritance model makes any sense. Inheritance promotes a IS_A relationship. Can we say a forward switching light IS_A backward switching light? What would make more sense is to have a base class that represents a light and then sub class it for forward and backward switching
0
 
LVL 40

Expert Comment

by:mrjoltcola
Comment Utility
You may consider creating an enum for light states.

enum LightState {
  Stop,
  PrepareToGo,
  Go,
  PrepareToStop
}


Then you declare a variable of LightState


LightState light_state = Stop;

etc.
0
 
LVL 40

Expert Comment

by:mrjoltcola
Comment Utility
0
 

Author Comment

by:glynn19872000
Comment Utility
to make it more clear, this work requires that I inherit from the normally cycling lights class when writing the reverse cycling lights class. it is merely academic/theoretical.

@ mrjoltcola: can this enumeration be inherited by other classes or is the scope of its use narrower?
How would I write such a thing if it can be inherited?

thanks.
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
Well, looking at your current class you don't have anything useful to inherit. The point of inheritance is to specialize or override existing behavior. Since traffic_light only contains a single function that's all you can override and the way it's currently written means you'd have to re-implement it completely for reverse lights.

>> this work requires that I inherit from the normally cycling lights class when writing the reverse cycling lights class. it is merely academic/theoretical.

This was stipulated in the text? Really? It's a really really poor inheritance model for the reasons I've already stated.
0
 
LVL 40

Expert Comment

by:mrjoltcola
Comment Utility
An enumeration is a type in itself. So a LightState becomes a type that can be used by anyone. Your class hierarchy is a separate thing in my opinion.

enumerations are useful for specifying integral types with discrete values (hot/cold, on/off, red/green/blue, small/medium/large).

We don't really think of OOP with enums (at least I don't) as they are meant to be efficient and treated as simple integers.
0
 

Author Comment

by:glynn19872000
Comment Utility
"This was stipulated in the text? Really? It's a really really poor inheritance model for the reasons I've already stated."

The traffic_light class is something I wrote myself which I guess explains its unsuitability as a good base for inheriting from!
I kept it as it compiles and runs, giving me the solution to the first part of the work. When it runs and the user press enters, it cycles round the light states correctly.
Are you saying I will have to rewrite the first class in order to do the second?
thanks again evilrix.
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
The pseudo C# below shows how I'd probably implement this. The enum tells the base class which direction to go in and you just sub class lights with forward or backward specializations, passing int he appropriate enum value into the base class constructor.
enun eDirection { FORWARD, BACKWARD };
 

class lights

{

     lights(eDirection);

}
 

class forward_lights : lights

{

     forward_lights(): 

        base(FORWARD){}

}
 

class backward_lights : lights

{

     forward_lights(): 

        base(BACKWARD){}

}

Open in new window

0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
>> Are you saying I will have to rewrite the first class in order to do the second?
I'm saying the current class is not suitable for inheriting since you have nothing that can be specialized or overriden in any useful way. If could; however, be used as an abstract base class (the lights class in my previous example), with the enum value dictating which way to switch the lights (++ for FORWARD and -- for BACKWARD).

BTW: I've just noticed mrjoltcola also suggested using an enum so consider this an extension on what he's suggested.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 40

Expert Comment

by:mrjoltcola
Comment Utility
I'm in agreement with evilrix. The enum, in my opinion, is simply a nice, clean alternative to arbitrary integers, or #define constants, etc.

Classes are meant for specialization and reuse through inheritance. enum is just a domain specific building block. I've not really commented in your class at all, as rix has that covered, I think.

I just think the array notation you started with is not the best approach for real world. Sure you might use that array for printing the messages, but for actually tracking / testing the state of the light, you want integral values (0, 1, 2, 3) for which enum is suited well.

0
 

Author Comment

by:glynn19872000
Comment Utility
thanks to both of you. from the actual specification, I was told to,
"...ensure that the implementation of reverse_cycling_traffic_light is a refinement by inheritance of the implementation of traffic_light.  
which gets at what I was on about earlier regarding inheritance.
0
 
LVL 40

Expert Comment

by:mrjoltcola
Comment Utility
Sure, understood.

evilrix sample shows that (though in pseudoce syntax).

I would write a cycle() method in the base class, and make it do a normal forward cycle.

The refinement is then done by subclassing into a new class, and overriding the cycle() method to reverse order.
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
The idea of specializing cycle() is a perfectly good example of how one might do this. I would suggest cycle be defined as an abstract function in the base class since it can't possible have an implementation without a specific direction.


>> though in pseudoce syntax
I'm too deep in C++ atm to remember C# syntax fully :)
0
 
LVL 40

Expert Comment

by:mrjoltcola
Comment Utility
Note I said "pseudoce", which is one step below pseudocode ... :P
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
>> Note I said "pseudoce", which is one step below pseudocode ... :P
I fear it was probably more like bs-code :)
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
Comment Utility
>>>> ensure that the implementation of reverse_cycling_traffic_light is a refinement by inheritance of the implementation of traffic_light.

I generally would like to admit that an abstract baseclass TrafficLights with two derived classes ForwardTrafficLights  and BackwardTrafficLights is a consistent model. But, the above requirements which only tells of two classes isn't as bad as some early comments may have stated. Think of an iterator class which maybe derived by reverse_iterator. We don't have iterator, forward_iterator and reverse_iterator but only the first and the last.

So a class TrafficLightsCycle where the iterating function or operator was virtual and could be overridden by a derived class ReverseTrafficLightsCycle could be well-defined if the iterating property wasn't determined by data members but by the virtual function only.  
0
 

Author Comment

by:glynn19872000
Comment Utility
"The idea of specializing cycle() is a perfectly good example of how one might do this. I would suggest cycle be defined as an abstract function in the base class since it can't possible have an implementation without a specific direction."

How would the cycle() function look in evilrix's pseudocode example?
Would I simply place cycle() in the base class, define its normal forward function then specialise this when I inherit it in the reverse class by reversing for loop or something?
0
 
LVL 40

Accepted Solution

by:
evilrix earned 500 total points
Comment Utility
>> How would the cycle() function look in evilrix's pseudocode example?
Pseudo code example below... you already know how to implement cycle since since it's just what you've already done but either forwards or reverse.

abstract class lights

{

   abstract virtual cycle();

}

 

class forward_lights : lights

{

   override cycle();

}

 

class backward_lights : lights

{

   override cycle();

}

Open in new window

0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now