[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Inheritance in C#...

Posted on 2009-06-30
18
Medium Priority
?
898 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
  • 4
  • +1
18 Comments
 
LVL 40

Expert Comment

by:evilrix
ID: 24745432
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
ID: 24745433
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
ID: 24745583
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:glynn19872000
ID: 24745696
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
ID: 24745793
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
ID: 24745821
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
ID: 24745834
"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
ID: 24745838
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
ID: 24745868
>> 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
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24745910
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
ID: 24746400
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
ID: 24746433
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
ID: 24746478
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
ID: 24746499
Note I said "pseudoce", which is one step below pseudocode ... :P
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24746524
>> 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
ID: 24748058
>>>> 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
ID: 24749337
"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 2000 total points
ID: 24751983
>> 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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

649 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