-2

I'm having trouble writing up some code. I'm not too sure where and how to write up the constructors and the accessors.

The activity I have to do is this:

Write 3 derived classes to allow a user to enter the details of three types of Vehicles with their attributes.

• Car (make, model, year, bodyType)

• Airplane (make, model, year, noEngines, engineType)

• Boat (make, model, year, length, hullType)

The 4th class is the base class Vehicle which contains the shared attributes and methods

Make all attributes either private (in derived classes) or protected (in base class) and write accessor methods for each attribute.

Write 2 constructors for each derived class. One with no arguments and the other which accepts the values of the attributes in the derived class as arguments.

Write a Console Application called Fleet.cs which creates and displays 2 of each Vehicle type

My code so far is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
    class Vehicle
    {
        static void Main(string[] args)
        {
        }

        class Car
        {
            protected string make
            {
                get
                {
                    return make;
                }
                set
                {
                    make = value;
                }
            }

            protected string model
            {
                get
                {
                    return model;
                }
                set
                {
                    model = value;
                }
            }

            protected int year
            {
                get
                {
                    return year;
                }
                set
                {
                    year = value;
                }
            }

            protected string bodyType
            {
                get
                {
                    return bodyType;
                }
                set
                {
                    bodyType = value;
                }
            }

            public bool isInitialized;
            public Car()
            {
                isInitialized = true;
            }
        }
    }

    class Airplane
    {
        protected string make
        {
            get
            {
                return make;
            }
            set
            {
                make = value;
            }
        }

        protected string model
        {
            get
            {
                return model;
            }
            set
            {
                model = value;
            }
        }

        protected int year
        {
            get
            {
                return year;
            }
            set
            {
                year = value;
            }
        }

        protected int numEngines
        {
            get
            {
                return numEngines;
            }
            set
            {
                numEngines = value;
            }
        }

        protected int engineType
        {
            get
            {
                return engineType;
            }
            set
            {
                engineType = value;
            }
        }
    }

    class Boat
    {
        protected string make
        {
            get
            {
                return make;
            }
            set
            {
                make = value;
            }
        }

        protected string model
        {
            get
            {
                return model;
            }
            set
            {
                model = value;
            }
        }

        protected string year
        {
            get
            {
                return year;
            }
            set
            {
                year = value;
            }
        }

        protected string length
        {
            get
            {
                return length;
            }
            set
            {
                length = value;
            }
        }

        protected string hullType
        {
            get
            {
                return hullType;
            }
            set
            {
                hullType = value;
            }
        }
    }
}
SlavisaB
  • 31
  • 1
  • 1
  • 7
  • 1
    where is your problem? are you asking us to write a code for you? – M.kazem Akhgary Jul 18 '15 at 06:17
  • Can anyone help please? I've been researching how to do this for days! – SlavisaB Jul 18 '15 at 06:18
  • No, I don't want the answer. I would like to know how the 'Fleet.cs' program can create and display vehicles types. I apologize if the structure of my question is wrong and if I'm missing details, I guess I was in a hurry to write it and to just get the task over and done with since I've been struggling with it for days! I'm new here but that't not an excuse to hurry. – SlavisaB Jul 18 '15 at 06:19
  • its ok. but your question is like asking to write code for me. if you dont know how to create instance of class and show the vehicle properties then [dotnetperls](http://www.dotnetperls.com/) is a good approach. how to [create instance of class](http://www.dotnetperls.com/new).class [properties](http://www.dotnetperls.com/property) – M.kazem Akhgary Jul 18 '15 at 06:29
  • I've done all the classes; base class and the 3 derived classes; "Car", "Airplane" and "Boat". I've made the attributes protected inside of the base class "Vehicle" and I've written 2 constructors for each derived class; constructor that doesn't take arguments and a constructor that takes the values of the attributes in the derived class as an argument (although now that I've re-read that constructor that takes arguments part that may be part of the problem). My (main?) problem is the console application part; how do I make the application create and display 2 of each vehicle type? – SlavisaB Jul 18 '15 at 06:35
  • @SlavisaB Look at my answer. – fsacer Jul 18 '15 at 06:43
  • 2
    include code in your code instead of just explaining what you have done. then people can help you better and you find your answer faster. dont put all your code but just classes and constructors. – M.kazem Akhgary Jul 18 '15 at 06:46
  • fsacer, I saw your comment and I've replied to it. – SlavisaB Jul 18 '15 at 06:56

2 Answers2

5

First part the OOP principles

Classes:

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable. For more information, see Static Classes and Static Class Members (C# Programming Guide). Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming. For more information, see Inheritance (C# Programming Guide).

Also objects are instances of classes.

Inheritance:

Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.

Derived class:
A class that was created based on a previously existing class (i.e., base class). A derived class inherits all of the member variables and methods of the base class from which it is derived. Also called a derived type.

Method:

A method (or message) in object-oriented programming (OOP) is a procedure associated with an object class. An object is made up of behavior and data. Data is represented as properties of the object and behavior as methods. Methods are also the interface an object presents to the outside world. For example a window object would have methods such as open and close. One of the most important capabilities that a method provides is method overriding. The same name (e.g., area) can be used for multiple different kinds of classes. This allows the sending objects to invoke behaviors and to delegate the implementation of those behaviors to the receiving object. For example an object can send an area message to another object and the appropriate formula will be invoked whether the receiving object is a rectangle,circle, triangle, etc.

Attributes and properties:

"Fields", "class variables", and "attributes" are more-or-less the same - a low-level storage slot attached to an object. Each language's documentation might use a different term consistently, but most actual programmers use them interchangeably. (However, this also means some of the terms can be ambiguous, like "class variable" - which can be interpreted as "a variable of an instance of a given class", or "a variable of the class object itself" in a language where class objects are something you can manipulate directly.)

"Properties" are, in most languages I use, something else entirely - they're a way to attach custom behaviour to reading / writing a field. (Or to replace it.)

So if you want to categorize them they are OOP(Object Oriented Programming) principles.

Second part:

Write a Console Application called Fleet.cs which creates and displays 2 of each Vehicle type.

So one way of doing this is creating vehicles as hardcoded. The other way is to ask user for vehicle details with Console.Readline(). Main method could look something like this.

static void Main(string[] args)
{
    Vehicle v1 = new Vehicle { Make = "test1", Model = "model1", Year = 1996 };
    Vehicle v2 = new Vehicle { Make = "test2", Model = "model2", Year = 1997 };
    Console.WriteLine(v1);
    Console.WriteLine(v2);
    ...
}

And then you would override the ToString() method for each class. Like this:

public override string ToString()
{
    return string.Format("Vehicle is {0} and of model {1} and is made in {2}.", make, model, year);
}

Here you also can use base.ToString() to get the data of upper (base) class in the derivided class.

EDIT 1: User input:

So if you want the user input you could make program like this:

static void Main(string[] args)
{
    //input
    Vehicle v1 = new Vehicle();
    Console.Write("Enter the make of 1st vehicle: ");
    v1.Make = Console.ReadLine();
    Console.Write("Enter the model of 1st vehicle: ");
    v1.Model = Console.ReadLine();
    Console.WriteLine("Enter the year of manufacturing for 1st vehicle:");
    v1.Year = int.Parse(Console.ReadLine());
    //output
    Console.WriteLine("The data for 1st vehicle: ");
    Console.WriteLine(v1);
    ...
}

Even better would be to create Input method in the class and calling it from Main program. So code would not be repeating itself.

Finished program

Vehicle.cs

using System;

class Vehicle
{
    string make, model;
    int year;

    public string Make { get { return make; } set { make = value; } }
    public string Model { get { return model; } set { model = value; } }
    public int Year { get { return year; } set { year = value; } }

    public Vehicle()
    {
        make = model = "Unknown";
        year = 0;
    }

    public Vehicle(string make, string model, int year)
    {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    public virtual void GetFromInput()
    {
        Console.Write("Enter the make of vehicle: ");
        Make = Console.ReadLine();
        Console.Write("Enter the model of vehicle: ");
        Model = Console.ReadLine();
        Console.WriteLine("Enter the year of manufacturing for vehicle: ");
        Year = int.Parse(Console.ReadLine());
    }

    public override string ToString()
    {
        return string.Format("Vehicle is {0} and of model {1} and is made in {2}.", make, model, year);
    }
}

Car.cs

using System;

class Car : Vehicle
{
    string bodyType;
    public string BodyType { get { return bodyType; } set { bodyType = value; } }

    public Car() : base()
    {
        bodyType = "Unknown";
    }

    public Car(string make, string model, int year, string bodyType) : base(make, model, year)
    {
        this.bodyType = bodyType;
    }

    public override void GetFromInput()
    {
        base.GetFromInput();
        Console.Write("Enter body type for the car: ");
        BodyType = Console.ReadLine();
    }

    public override string ToString()
    {
        return base.ToString() + string.Format("This vehicle is a car with body type of {0}.", BodyType);
    }
}

Airplane.cs

using System;

class Airplane : Vehicle
{
    int noEngines;
    string engineType;
    public int NumberOfEngines{ get { return noEngines; } set { noEngines = value; } }
    public string EngineType { get { return engineType; } set { engineType = value; } }

    public Airplane() : base()
    {
        noEngines = 0;
        engineType = "Unknown";
    }

    public Airplane(string make, string model, int year, int noEngines, string engineType) : base(make, model, year)
    {
        this.noEngines = noEngines;
        this.engineType = engineType;
    }

    public override void GetFromInput()
    {
        base.GetFromInput();
        Console.Write("Enter the number of engines on an airplane: ");
        NumberOfEngines = int.Parse(Console.ReadLine());
        Console.Write("Enter the engine type for the airplane: ");
        EngineType = Console.ReadLine();
    }

    public override string ToString()
    {
        return base.ToString() + string.Format("This vehicle is an airplane with {0} engines and engine type of {1}.", NumberOfEngines, EngineType);
    }
}

Boat.cs

using System;

class Boat : Vehicle
{
    int length;
    string hullType;
    public int Length { get { return length; } set { length = value; } }
    public string HullType { get { return hullType; } set { hullType = value; } }

    public Boat() : base()
    {
        length = 0;
        hullType = "Unknown";
    }

    public Boat(string make, string model, int year, int length, string hullType) : base(make, model, year)
    {
        this.length = length;
        this.hullType = hullType;
    }

    public override void GetFromInput()
    {
        base.GetFromInput();
        Console.Write("Enter the length of the boat: ");
        Length = int.Parse(Console.ReadLine());
        Console.Write("Enter the hull type for the boat: ");
        HullType = Console.ReadLine();
    }

    public override string ToString()
    {
        return base.ToString() + string.Format("This vehicle is a boat with length of {0} and hull type of {1}.", Length, HullType);
    }
}

Fleet.cs

using System;

class Fleet
{
    static void Main(string[] args)
    {
        Vehicle v1 = new Vehicle();
        v1.GetFromInput();
        Console.WriteLine(v1);
        //... for the other vehicles
    }
}
Community
  • 1
  • 1
fsacer
  • 1,382
  • 1
  • 15
  • 23
  • 1
    Firstly, thanks for the OOP Principles description, I knew how to use them but the descriptions were useful and specific, secondly, I'm going to use the code you've suggested to me and I'll come back to you with how it went, thirdly, I need user input for this task, would the difference be dramatic or a few tweaks away from what you've presented me? – SlavisaB Jul 18 '15 at 06:49
  • 1
    @SlavisaB added the user input part in the edit. Also if you find my answer useful upvote it and mark it as answer. – fsacer Jul 18 '15 at 06:58
  • I'm going to try it now! I'll reply back soon! – SlavisaB Jul 18 '15 at 07:01
  • I've updated my question. I've fixed up the structure and I've added my code so far. Could you please check it out and and reply back. – SlavisaB Jul 18 '15 at 08:26
  • @SlavisaB Well you've good a problem in your code. You aren't using inheritance at all. – fsacer Jul 18 '15 at 08:27
  • I'm aware of that. I don't know where to put what if you catch my drift. – SlavisaB Jul 18 '15 at 08:33
  • could you please explain why Make, Model and Year are light blue as if they are classes themselves? – SlavisaB Jul 18 '15 at 09:06
  • @SlavisaB Look at finished program. They are blue because Stackoverflow's syntax highlighthing isn't perfect. – fsacer Jul 18 '15 at 09:08
  • @SlavisaB Also could you mark my answer as an accepted one as I'm sure you find it useful. Just tick it, if you don't know how look at StackOverflow's tour for the new users. – fsacer Jul 18 '15 at 09:11
  • Thank you so much! I had to tweak a few things but you've helped me so much! If I could upvote 100 times I would! – SlavisaB Jul 18 '15 at 10:03
  • @SlavisaB I'm glad I can help. Did you figure out the array part? – fsacer Jul 18 '15 at 10:08
  • I've built the program and it works perfectly! Thank you so much fsacer for the help! :) – SlavisaB Jul 18 '15 at 10:36
0

This can be achieved using class inheritance.

Each of your vehicle classes, need to inherit a common class that implements functionality need by 'all' vehicles, This class (Vehicle receptively), can then be used in C# to identify any type of vehicle class/type.

Instead of having a several classes where each class is solely responsible for a type of vechile, you can abstract out common functionality needed by each vehicle, and implement a class that exposes these common relationships:

using System;

public namespace CodeSpace {
 public class Vehicle { 
  public Vehicle(Type type, string make, string model) {
   Model = model;
   Make = make;
   Type = type;
  }
  public Type VehicleType { get; private set; }
  public string Make { get; set; } 
  public string Model { get; set; } 
 }

 public class Airplane : Vehicle {
  public class Airplane(string make, string model) : base(typeof(Airplane), make, model) {
  }
 }

 public class Boat : Vehicle {
  public class Boat(string make, string model) : base(typeof(Boat), make, model) {
  }
 }

 public class Car : Vehicle {
  public class Car(string make, string model) : base(typeof(Car), make, model) {
  }
 }

 class Program {
 public static void Main(params string[] args ) {       
 var vehicles = new List<Vehicle>() {
    new Boat("Canoe", "X2") as Vehicle,
    new Boat("Raft", "A") as Vehicle,
    new Car("Ford", "T") as Vehicle,
    new Airplane("BMW", "Idk") as Vehicle,
 };

  foreach(var v in vehicles) { 
   Console.WriteLine(v.VehicleType.FullName);
  }
 }
}

}

Now all of your vehicles can be identified using one class that exposes all vehicles through a common interface.

zackery.fix
  • 1,786
  • 2
  • 11
  • 20
  • "Type is a type but is used like a variable" How can I fix this? – SlavisaB Jul 18 '15 at 09:56
  • 1
    @SlavisaB That's because there's an error in the `foreach` loop. It should be `Console.WriteLine(v.VehicleType.FullName);`. – fsacer Jul 18 '15 at 10:07
  • Interesting code, but unfinished and maybe overly complex. Also there could be improvement with using Collection initializers to make code more readable. – fsacer Jul 18 '15 at 10:11
  • @fscar Thanks for the suggestions! SlavisaB I don't want you to take this the wrong way, but the biggest challenge in programming is correcting errors and finding out how your code works. Stackoverflow is meant to aid or assist in development, and not have your hand held the entire time. If there is ever such a non-trivial error in example code on this site, suggestions are an obvious way of helping others who see the example, but you didn't even try finding a solution to the problem. I post code like that to troll for bad habits, and lack of research is the most common bad habit. – zackery.fix Dec 28 '15 at 15:58
  • @fscar Software is complex, and inheritance is possibly the most complex 'feature' of modern the OOP paradigm. I was illustrating this using a very simple example, as inheritance can be way more complex than what I describe here. Anyway, thank you for the suggestions, I made my edits and if you have anymore suggestions, please feel free to comment! Happy programming! – zackery.fix Dec 28 '15 at 16:02