Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help on a windows based Inheritance

Status
Not open for further replies.

DarkWorlds

Technical User
Jul 20, 2005
64
US
Im supposed to be doing Inheritance on the console line, and well all is semi ok. But what im confused on is how do this in a windows design.

I am trying to complete something, but I dont even know where to start.

I was hoping someone could help me. Here are what I need for classes. And what they have to do. of course this all posts up on a listbox.

Ive tried this with console and for the most part i got it working, but it was static info in the code, but the same setup in windows i have no clue.

The base class will be Vehicle. The Car and Truck classes will inherit from the Vehicle class. The Vehicle class will be composed of an object of the FuelTank class. The FuelTank class has 2 attribute variables: (mTankCapacity and mCurrentValue).

In addition to the FuelTank object, the attribute variables of the Vehicle class are: mVehID, mDesc, mOdometer, and mMPG. In addition to setting up properties for the variables as needed, the Vehicle class has the following methods: AddFuel() - receives the amount of fuel to be added to the tank and adds that to the tank if the tank will hold it. If it will, it returns a true; otherwise, a false. FillTank() – fills the tank and returns a string indicating the amount of gallons added to the tank.

The attribute variable of the Car class is mNumRiders. The methods of the Car class are: getMPG() – a method that calculates the current MPG. The MPG is reduced by 2% for every rider over 1. (For example if the car's mpg is 28.5 and there are 5 riders, the current mpg is 26.22). MoveForward() – receives the mileage to move forward. The method determines if there is enough fuel to make the trip. If not, it returns false. If there is enough fuel to make the trip, the mileage is added to the odometer and the gas tank is reduced by the amount of gas needed for the trip.

The attribute variable of the Truck class is mLoadLbs. The methods of the Truck class are: getMPG() – a method that calculates the current MPG. The MPG is reduced by 3% for every thousand pounds if the load is >= 1,000 pounds. For example if the truck's mpg is 13.4 and is loaded with 4000 pounds, the current mpg is 11.79. Another example is if the truck's mpg is 13.4 loaded with 500 pounts, the current mpg is 13.4. MoveForward() – receives the mileage to move forward. The method determines if there is enough fuel to make the trip. If not, it returns false. If there is enough fuel to make the trip, the mileage is added to the odometer, the gas tank is reduced by the amount of gas needed for the trip, and the method returns true.

So thats the classes, go give a visual refrence there is a listbox, a move forward button and a add fuel button.

I would honestly love the help on where to go with this, I am so lost but yet i really need to see a sample of this coded. All the samples I have are in console (look around the web and they all are) I would just like to see a sample like this in a windows format, seeing how its way more confusing.

Please I am really looking for help, if you wish to email me then fine, or something. As long as i can figure out how this dumb program goes. This is what you get when you get a lab book to teach your self but no teacher edition. *sigh* I look forward to your help.
 
JurkMonkey you where a huge help...

Got a good example of polymorphism? Your last one helped me out quite a bit.

Im tired of the console crud when the book asks you to do windows form... lol
 

This has a simple example.

Basically, you declare methods in your base class as virtual or abstract. The classes that you extend from this class can override these methods and modify them on their own.

For example:

public bool AddFuel(double addGas)

this is from the Vehicle class. You could make it virtual or abstract,
when you extend truck, you could say "Adding Diesel"
when you extend car, you could say "Adding Gasoline"

Check out the article though. It's funny because I use this all the time, I just didn't realize that it is "polymorphism". I had to actually look up what the meaning was again. Eventually it just becomes routine.
 
I have to add to: when it comes to the console programming and then windows forms after - the idea is that you should be able to have all your data working purely on a data basis. This means there are no views (Forms etc.) influencing the data process. The windows forms should then be built on top of the data (console stuff) to display and interact with the data.

It's actually a very good practice. Too many people, including myself, get caught up in the GUI side of things.

I love GUI
 
Hmm... read all that. But still it kinda helped. Load pounds and passenger change doesnt work. Trying to make the polymorphic is hard. And I dont know if I am doing it right. Also is the if (vehicle = car) the correct thing to use in that area? Heres what I have right now, note it is not working because of the load pounds and passengers

No im not useing the array yet, just trying to get it to work with the 2 vehicles right now.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace polymorphic
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnSwitch;
private System.Windows.Forms.Button btnMove;
private System.Windows.Forms.Button btnRandom;
private System.Windows.Forms.Button btnFuel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

Vehicle[] veharray = {
new Car (877,"Camry", 24567,28.5,15.4,12.6,5),
new Car (951,"Accord", 9815,26.1,14.8,9.1,1),
new Car (986,"Corvette", 12970,12.5,17.3,4.3,2),
new Car (989,"Crown Victoria", 35978,13.2,18.5,5.1,3),
new Car (1023,"Firebird", 64135,11.3,14.6,8.9,2),
new Truck(1214,"F-150",8754,13.4,26.6,10.3,4000.0),
new Truck(1237,"Tundra",1234,12.4,24.6,9.2,1236.4),
new Truck(1328,"Yukon",8326,11.6,30.1,28.4,0.0),
new Truck(1490,"Silverado",27819,8.9,35.8,17.5,2567.8)
};

Car car = new Car(877,"Camry", 24567,28.5,15.4,12.6,5);
Truck truck = new Truck(124,"F-150",8754,13.4,26.6,10.3,4000.0);


private System.Windows.Forms.Label lblCombo;
private System.Windows.Forms.TextBox txtCombo;
private System.Windows.Forms.RichTextBox rtbView;
private System.Windows.Forms.Button btnCombo;
Vehicle vehicle;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
vehicle = car;
Display();
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnSwitch = new System.Windows.Forms.Button();
this.btnMove = new System.Windows.Forms.Button();
this.btnRandom = new System.Windows.Forms.Button();
this.btnFuel = new System.Windows.Forms.Button();
this.btnCombo = new System.Windows.Forms.Button();
this.txtCombo = new System.Windows.Forms.TextBox();
this.lblCombo = new System.Windows.Forms.Label();
this.rtbView = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// btnSwitch
//
this.btnSwitch.Location = new System.Drawing.Point(19, 160);
this.btnSwitch.Name = "btnSwitch";
this.btnSwitch.Size = new System.Drawing.Size(163, 26);
this.btnSwitch.TabIndex = 0;
this.btnSwitch.Text = "Switch Vehicles";
this.btnSwitch.Click += new System.EventHandler(this.btnSwitch_Click);
//
// btnMove
//
this.btnMove.Location = new System.Drawing.Point(248, 160);
this.btnMove.Name = "btnMove";
this.btnMove.Size = new System.Drawing.Size(163, 26);
this.btnMove.TabIndex = 1;
this.btnMove.Text = "Move Foward";
this.btnMove.Click += new System.EventHandler(this.btnMove_Click);
//
// btnRandom
//
this.btnRandom.Location = new System.Drawing.Point(19, 224);
this.btnRandom.Name = "btnRandom";
this.btnRandom.Size = new System.Drawing.Size(163, 26);
this.btnRandom.TabIndex = 2;
this.btnRandom.Text = "Random Move";
this.btnRandom.Click += new System.EventHandler(this.btnRandom_Click);
//
// btnFuel
//
this.btnFuel.Location = new System.Drawing.Point(248, 224);
this.btnFuel.Name = "btnFuel";
this.btnFuel.Size = new System.Drawing.Size(163, 26);
this.btnFuel.TabIndex = 3;
this.btnFuel.Text = "Add Fuel";
this.btnFuel.Click += new System.EventHandler(this.btnFuel_Click);
//
// btnCombo
//
this.btnCombo.Location = new System.Drawing.Point(96, 288);
this.btnCombo.Name = "btnCombo";
this.btnCombo.Size = new System.Drawing.Size(230, 27);
this.btnCombo.TabIndex = 8;
this.btnCombo.Text = "Change Number of Riders";
this.btnCombo.Click += new System.EventHandler(this.btnChange_Click);
//
// txtCombo
//
this.txtCombo.Location = new System.Drawing.Point(259, 360);
this.txtCombo.Name = "txtCombo";
this.txtCombo.Size = new System.Drawing.Size(120, 22);
this.txtCombo.TabIndex = 5;
this.txtCombo.Text = "";
this.txtCombo.Visible = false;
this.txtCombo.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtCombo_KeyDown);
//
// lblCombo
//
this.lblCombo.Location = new System.Drawing.Point(48, 360);
this.lblCombo.Name = "lblCombo";
this.lblCombo.Size = new System.Drawing.Size(202, 37);
this.lblCombo.TabIndex = 6;
this.lblCombo.Visible = false;
//
// rtbView
//
this.rtbView.Location = new System.Drawing.Point(19, 18);
this.rtbView.Name = "rtbView";
this.rtbView.ReadOnly = true;
this.rtbView.Size = new System.Drawing.Size(394, 118);
this.rtbView.TabIndex = 9;
this.rtbView.Text = "";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(432, 431);
this.Controls.Add(this.rtbView);
this.Controls.Add(this.lblCombo);
this.Controls.Add(this.txtCombo);
this.Controls.Add(this.btnCombo);
this.Controls.Add(this.btnFuel);
this.Controls.Add(this.btnRandom);
this.Controls.Add(this.btnMove);
this.Controls.Add(this.btnSwitch);
this.Name = "Form1";
this.Text = "Vehicle Control System";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());

}

public class FuelTank
{
private double mTankCapacity;
private double mCurrentValue;
public FuelTank(double tankCapacity,double currentValue)
{
mTankCapacity = tankCapacity;
mCurrentValue = currentValue;
}

public double TankCapacity
{
get
{
return mTankCapacity;
}
set
{
mTankCapacity = value;
}
}

public double CurrentValue
{
get
{
return mCurrentValue;
}
set
{
mCurrentValue = value;
}
}
}

public abstract class Vehicle
{
private int mVehID;
private string sDesc;
private double mOdometer;
private double mMPG;
private FuelTank fueltank;
private double mCurrentValue;
public Vehicle(int vehID, string desc, double odometer, double tankCapacity,
double currentValue,double mpg)
{
mVehID = vehID;
sDesc = desc;
mOdometer = odometer;
mMPG = mpg;
fueltank = new FuelTank(tankCapacity,currentValue);
mCurrentValue = currentValue;
}
public virtual bool AddFuel(double addGas)
{
double temp;
temp = addGas;
if(CurrentValue + temp > TankCapacity)
{
return false;
}
else
{
CurrentValue += addGas;
return true;
}
}
public override string ToString()
{
return String.Format("Vehicle ID: {0}\nDescription: {1}\nOdometer:"+"{2:N}\nFuel Tank Capacity: {3:N}\nCurrent Value {4:N}",VehID,Desc, Odometer, TankCapacity, CurrentValue);
}


public virtual string FillTank()
{
double gallonsAdded;
gallonsAdded = TankCapacity - CurrentValue;
CurrentValue += gallonsAdded;
return String.Format("You added {0:N} gallons to the tank",
gallonsAdded);
}
public virtual bool MoveForward(double mile)
{
if(CurrentValue * getMPG() >= mile)
{
Odometer += mile;
CurrentValue = (CurrentValue * getMPG() - mile) / getMPG();
return true;
}
else
return false;
}


public int VehID
{
get
{
return mVehID;
}
set
{
mVehID = value;
}
}


public string Desc
{
get
{
return sDesc;
}
set
{
sDesc = value;
}
}


public double Odometer
{
get
{
return mOdometer;
}
set
{
mOdometer = value;
}
}


public double MPG
{
get
{
return mMPG;
}
set
{
mMPG = value;
}
}


public double CurrentValue
{
get
{
return fueltank.CurrentValue;
}
set
{
fueltank.CurrentValue = value;
}
}


public double TankCapacity
{
get
{
return fueltank.TankCapacity;
}
set
{
fueltank.TankCapacity = value;
}
}
public virtual int NumRiders
{
get
{
return mNumRiders;
}
}

public virtual double LoadPounds()
{
return 0;
}

public virtual double getMPG()
{
return 0;
}
}

public class Car : Vehicle
{
private int mNumRiders;
public Car(int vehID, string desc, double odometer, double mpg,
double tankCapacity,double currentValue, int numRiders):
base (vehID, desc, odometer,tankCapacity,currentValue, mpg)
{
mNumRiders = numRiders;
}
public int NumRiders
{
get
{
return mNumRiders;
}
set
{
mNumRiders = value;
}
}
public override double getMPG()
{
if(NumRiders > 1)
{
return MPG - ((MPG * .02)*(NumRiders - 1));
}
else
return MPG;
}
public override string ToString()
{
return base.ToString () + String.Format("\nMPG: {0:N}\nNumber Riders: {1}", getMPG(),NumRiders);
}

}


public class Truck : Vehicle
{
private double mLoadPounds;
public Truck(int vehID, string desc, double odometer, double mpg,
double tankCapacity,double currentValue, double loadPounds):
base (vehID, desc, odometer,tankCapacity,currentValue, mpg)
{
mLoadPounds = loadPounds;
}
public double LoadPounds
{
get
{
return mLoadPounds;
}
set
{
mLoadPounds = value;
}
}
public override double getMPG()
{
if(LoadPounds >= 1000)
return MPG - ((MPG * .03)*(LoadPounds / 1000));
else
return MPG;
}
public override string ToString()
{
return base.ToString () + String.Format("\nMPG: {0:N}\nLoad Pounds: {1}", getMPG(),LoadPounds);
}
}

private void btnMove_Click(object sender, System.EventArgs e)
{
txtCombo.Clear();
lblCombo.Text = "Enter Milage";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();
}

private void btnRandom_Click(object sender, System.EventArgs e)
{
Random RandomNum = new Random();
int RandomMile = RandomNum.Next(0,301);
string message = String.Format("Moving foward {0} miles", RandomMile);
txtCombo.Hide();
lblCombo.Hide();

if(vehicle.MoveForward(RandomMile) == false)
{
MessageBox.Show("Not enough gas for trip of " + RandomMile + " miles",
"MILEAGE STATUS");
return;
}
else
MessageBox.Show(message,"MILEAGE STATUS",MessageBoxButtons.OK,
MessageBoxIcon.None);
Display();
}

private void btnFuel_Click(object sender, System.EventArgs e)
{
txtCombo.Clear();
lblCombo.Text = "Enter amount of gas (0 to fill tank)";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();

}


private void btnChange_Click(object sender, System.EventArgs e)
{
txtCombo.Clear();
if (vehicle is Car)
{
lblCombo.Text = "Enter Number of Riders (1 - 6)";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();
}
else if (vehicle is Truck)
{
lblCombo.Text = "Enter Load Pounds (0 - 8000)";
lblCombo.Show();
txtCombo.Show();
txtCombo.Focus();
}
}


private void txtCombo_KeyDown(object sender, System.Windows.Forms.KeyEventArgs combo)
{
double input = 0;
if(combo.KeyCode == Keys.Enter)
{
try
{
input = double.Parse(txtCombo.Text);
}
catch
{
MessageBox.Show("Invaild Input","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
return;
}
if(lblCombo.Text == "Enter Milage")
{
if(input < 0)
{
MessageBox.Show("No Negitive Numbers","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
}
else
{
if(vehicle.MoveForward(input) == false)
{
MessageBox.Show("Not enough gas for trip of " + input + " miles",
"MILEAGE STATUS");
txtCombo.Clear();
txtCombo.Focus();
return;
}
else
{
txtCombo.Hide();
lblCombo.Hide();
}
}
}
else if(lblCombo.Text == "Enter amount of gas (0 to fill tank)")
{
if(input < 0)
{
MessageBox.Show("No negitive numbers","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
}
else
{
if(input == 0)
MessageBox.Show(vehicle.FillTank(),"Gas Status");
else if(!vehicle.AddFuel(input))
{
MessageBox.Show("The tank can not hold that much gas","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
txtCombo.Hide();
lblCombo.Hide();
}
}
}
else if(vehicle is Car)
{
if(input < 1 || input > 6)
{
MessageBox.Show("Invalid Number of Riders","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
return;
}
else
{
vehicle.NumRiders = (int)input;
vehicle.getMPG();
txtCombo.Clear();
txtCombo.Hide();
lblCombo.Hide();
}
}
else if(vehicle is Truck)
{
if(input < 0 || input > 8000)
{
MessageBox.Show("Invalid Load Pounds","ERROR",MessageBoxButtons.OK,
MessageBoxIcon.Error);
txtCombo.Clear();
txtCombo.Focus();
return;
}
else
{
vehicle.LoadPounds();
vehicle.getMPG();
txtCombo.Clear();
txtCombo.Hide();
lblCombo.Hide();
}
}

}
Display();
}


private void btnSwitch_Click(object sender, System.EventArgs e)
{
txtCombo.Clear();
txtCombo.Hide();
lblCombo.Hide();
if (vehicle is Car)
{
btnCombo.Text = "Change Load Pounds";
vehicle = truck;
}

else if (vehicle is Truck)
{
btnCombo.Text = "Change Number of Riders";
vehicle = car;
}
Display();
}


private void Display()
{
rtbView.Text = vehicle.ToString();
}
}
}
 
Here's your stumbling block:
Code:
else if(vehicle is Car)
{
  if(input < 1 || input > 6)
  {
    MessageBox.Show("Invalid Number of Riders","ERROR",MessageBoxButtons.OK,
      MessageBoxIcon.Error);
    txtCombo.Clear();
    txtCombo.Focus();
    return;
  }
    else
  {
    vehicle.NumRiders = (int)input;
    vehicle.getMPG();
    txtCombo.Clear();
    txtCombo.Hide();
    lblCombo.Hide();
  }
}
Instead of asking each type of vehicle what it's passenger limits are, you should add a virtual method to their base class (something like NotOverPassengerLimit()) that each type of vehicle would override. You would then call the base method, which automatically gets routed to the correct child class. That results in not needing a lot of "if is car" and "if is bicycle" type of code. You'd only have to say:
Code:
if (MyVehicle.NotOverPassengerLimit())
which is much simpler, cleaner, and a more correct implementation of polymorphism.

Chip H.

____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
well car is passengers (1-6)
and truck is load pounds (0-8000)

So im not sure how I should go about this. I was given a method of getVehType() but in that would be if car then c and if truck than t and base that if stament on that

But from how i look at it, my if stement is the same now...

I am lost when it comes to this.

 
It's probably time to ask your professor for help, then.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top