my last problem is with inheritance in C#. I thought I understood this topic but somehow I am missing the point why the output is like that.
Here are my classes:
BaseClass:
public abstract class Vehicle
{
public Vehicle()
{
Console.WriteLine("Honda Civic");
}
public abstract void Display();
}
Derived Class 1:
public class Vehicle4Wheels : Vehicle
{
public override void Display()
{
Console.WriteLine("Derived111 class Constructor.");
}
}
Derived Class 2:
public class SportCar : Vehicle4Wheels
{
public new void Display()
{
Console.WriteLine("Derived222 class Constructor.");
base.Display();
}
}
This is the hierarchy: Base Class -> Derived Class 1 -> Derived Class 2
This is the output I am getting:
Honda Civic
Derived222 class Constructor.
Derived111 class Constructor.
This is the output I am trying to achieve:
Honda Civic
Derived111 class Constructor.
Derived222 class Constructor.
I have read several articles where it was stated that base class is printed first and the other derived classes are printed based on their spot in the hierarchy.
So why is the last derived class printed before the first derived class? What am I missing (except C# programming skills)?
Thank for the answers.
EDIT:
I am sorry it took me a while to get back to this thread. To be more precise, I will post the task of the homework I am trying to achieve:
Work 2:
An abstract class is not a complete class, it misses some parts, and you cannot create
objects from it. The programmer who writes the derived classes must fill in the missing
parts. Consider an abstract class Vehicle. Derive two hierarchies from this class as it
is shown below: Now, write 4 classes, see the yellow rectangle. Start from the abstract
base class Vehicle -> Vehicle with 4 wheels -> Sport Cars and stop at the derived class Rally, which is the most specific
class. The class Vehicle contains a field which holds the vehicle name and an abstract
method void Display().
Implement this function in the derived classes, so that the function returns
information about the vehicle, e.g. the motor power and other necessary properties. The
last derived class has private fields to hold the motor power, the car weight, the car
acceleration, the highest speed and a function that computes the specific power (power
/ weight). The function Display returns a text string with all this information. Test
your work in a Console application that uses objects of the type of the classes Sport
car and Rally.
Class Vehicle:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace A_work_2
{
public abstract class Vehicle
{
public string vehicleName;
public abstract void Display();
}
}
Class Vehicle4Wheels:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace A_work_2
{
public class Vehicle4Wheels : Vehicle
{
public override void Display()
{
Console.WriteLine("Car1");
}
}
}
Class SportCar:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace A_work_2
{
public class SportCar : Vehicle4Wheels {
public override void Display()
{
Console.WriteLine("Derived222 class Constructor.");
}
}
}
Class Rally:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace A_work_2
{
public class Rally : SportCar
{
private double motorPower = 408;
private double carWeight = 2380;
private double carAcceleration = 4.7;
private double highestSpeed = 250;
public double SpecificPower()
{
double specificPower = motorPower / carWeight;
return specificPower;
}
public override void Display()
{
Console.WriteLine("The acceleration is: {0}.\nThe highest speed is {1} km/h.", carAcceleration, highestSpeed);
Console.WriteLine("Specific power is {0}", SpecificPower());
}
}
}
I am not sure how to achieve the goal of the task with abstract methods.
Thank you for answers, V.
You are mixing the concept of a constructor with the concept of a virtual method. Constructors are indeed called in order from base to derived, but you have created non-constructor virtual methods.
This will give the output you wanted:
// In Vehicle4Wheels
public Vehicle4Wheels()
{
Console.WriteLine("Vehicle4Wheels constructor");
}
// In SportCar
public SportCar()
{
Console.WriteLine("SportCar constructor");
}
(Also, edit the string you are printing in the Display() methods, since they are misleading - Display() is not a constructor.)
As for virtual methods (note that abstract methods automatically become virtual), the "most derived" class' method is the one that is called, and only that method is called - unless the method invokes base.MethodName().
This is the output I am getting: Honda Civic Derived222 class
Constructor. Derived111 class Constructor.
This is the output I am trying to achieve: Honda Civic Derived111
class Constructor. Derived222 class Constructor.
Ok, just swap the calls:
public new void Display()
{
base.Display();
Console.WriteLine("Derived222 class Constructor.");
}
You first Get Honda Civic because it is output during the creation of the base class. the constructors of the base class is the first thing that is perform during the constructor of the inherited class.
Then you Get Derived222 because it is output first in your display method.
Change your code that way :
public abstract class Vehicle {
public Vehicle() { Console.WriteLine("Honda Civic"); }
}
public class Vehicle4Wheels : Vehicle {
public Vehicle4Wheels() { Console.WriteLine("Derived111 class Constructor."); }
}
public class SportCar : Vehicle4Wheels {
public SportCar() { Console.WriteLine("Derived222 class Constructor.");
}
you don't need to override the Display() method in what you(re trying to achieve.
And beware of the use of the new keyword when declaring a method ;-)
You didn't show the code you are using to test your classes, but I think it is something like this:
SportCar car = new SportCar();
car.Display();
The first thing that is not so clear is why you are writing on the console in the constructor of the abstract class, but in a method of the derived ones. This means that, apart from the order of the messages, Honda Civic is written as soon as you create an instance of each one of your classe, while the other messages are written only when you call the Display method (even if you write Constructor in the method).
#Seb gave you the right way to go if you want to do specific things in the constructors of a hierarchy of classes, but if you really wanted to write different versions of the method Display, you must be careful to the use of override and new. If a method is virtual or abstract, you should always use override, and leave the use of new to the cases in which you want to hide the method defined in the base classes. You can find an example (using cars like you :-)) here: [http://msdn.microsoft.com/en-us/library/ms173153(v=vs.80).aspx].
If you use override, the method being executed is determined at run time and depends on the type of the object. If you use new the method being executed is determined at compile time and depends on the type of the variable you assign your object to. For instance, if you execute this piece of code with your classes:
Console.WriteLine("This is the constructor");
SportCar car = new SportCar();
Console.WriteLine("This is the first call to display");
car.Display();
Vehicle4Wheels car2 = car;
Console.WriteLine("This is the second call to display");
car2.Display();
The result is:
This is the constructor
Honda Civic
This is the first call to display
Derived222 class Constructor.
Derived111 class Constructor.
This is the second call to display
Derived111 class Constructor.
Replacing the new with an override you obtain what you are probably expecting:
This is the constructor
Honda Civic
This is the first call to display
Derived222 class Constructor.
Derived111 class Constructor.
This is the second call to display
Derived222 class Constructor.
Derived111 class Constructor.
Related
I'm starting to learn how to create C# and using Interface and Class.
Can someone teach me how to separate my Class and my Interface and still maintain their connection from one another?
Reason: If I'll be updating my code, I'll know where to add them and it will be less code in my screen.
namespace Car
{
class MainClass
{
//My Interface
interface ICar
{
int gas { get; set; }
//void refuel();
int getGasLeft();
}
//My Class
class Car : ICar
{
public int gas { get; set; }
public Car(string _name)
{
name = _name;
dist = 0;
gas = 40;
}
public void refuel(int lit)
{
gas += lit;
}
public int getGasLeft()
{
return gas;
}
}
//Main
public static void Main(string[] args)
{
Car toyota = new Car();
toyota.drive(100);
toyota.refuel(5);
Console.WriteLine("Name: " + toyota.name +
"\nGas Left: " + toyota.getGasLeft());
Console.ReadLine();
}
}
}
In C#, a namespace is the way to connect files from different places.
For example, you can make a folder Interfaces and put your ICar there. I will show you an example from my project.
My folder structure looks like this:
In my ViewModel.cs I use an object named FakeData. As you can see below, class FakeData is in the TaskManager.Models namespace.
Now, we are going to our project and we are looking at the Models folder.
In C#, when you create a folder and a class in it, you will get a namespace based on your folder name. Of course, you can change it. You can edit the namespace how you want to.
In your case, you can simply make a folder called Interfaces. Right click, then select New Class, and give it a name, for example, Icar.cs. Paste your code there. Your default namespace will be ProjectName.Interfaces. Make your interface public. Then, you can call your interface by adding using ProjectName.Interfaces in the top of your main class. Then you can do Main : ICar without any errors.
Same idea with the Car class. You can make a folder named Models and a class in it that called Cars.cs. It will have the namespace ProjectName.Models. If you want to use your interface that is in Interfaces folder, you need to add a namespace to your Car.cs class. In your case, it will look like using ProjectName.Interfaces. Then, you can call the interface in Car.cs without any error.
Feel free to ask me any questions about this. I will try to help you.
You need to learn about public, private, protected, namespaces, and so on.
On your case, create a new file called ICar.cs in the same folder and declare it as public interface in the same namespace.
I have a namespace that will change somewhat frequently in my project (each product generation) and would like to keep references to that specific namespace contained to the file where I define a base class. In other files I define child classes that usually can get by with getting references to the namespace by inheritance, but I am having trouble with one case as the objects are very specific and I would prefer to link to the namespace within the base class rather than each object.
BaseClass.cs
namespace CommonNameSpace
{
using _productSpecificNameSpace;
_productSpecificNameSpace.thing.otherthing thingotherthingGood = _productSpecificNameSpace.thing.otherthing.Success;
_productSpecificNameSpace.thing.otherthing thingotherthingBad = _productSpecificNameSpace.thing.otherthing.SpecificFailure;
public class BaseClass
{
}
}
SubClass.cs
namespace CommonNameSpace
{
public class SubClass : BaseClass
{
var yeaOrNeigh = thingotherthingGood
}
}
How can I access _productSpecificNameSpace in SubClass.cs without having to call it _productSpecificNameSpace in each subclass, or name every possible object that I will need in BaseClass? Is there a way to get an alias to a namespace attached to a class for inheriting?
Edit: Ideally, I would like to have access to the data types in the interchangeable namespace, as it is mostly a library of enums. Wouldn't having an interface replace the type of these enums with an interface type that would be incomparable with calls to APIs expecting the underlying type?
If you use an interface, you can then instantiate the generation you want to at runtime, without affecting any existing code:
interface IMyThing
{
void DoStuff()
}
abstract class BaseThing : IMyThing
{
public virtual void DoStuff()
}
Generation1:
class MyGen1 : BaseThing
{
public override void DoStuff()
{
// I'm Gen 1
}
}
Generation2:
class MyGen2 : BaseThing
{
public override void DoStuff()
{
// I'm Gen 2
}
}
I have this code :
namespace ConsoleApplicationDemo
{
class base
{
public virtual void Sum()
{
Console.WriteLine("Sum in base ");
}
}
class Program:base
{
public override void Sum()
{
Console.WriteLine("SUM IN Program ");
}
static void Main(string[] args)
{
base A2 = new Program();
A2.Sum();
Program P2 = new Program();
P2.Sum();
Console.ReadLine();
}
}
}
getting OutPUT: SUM IN Program SUM IN Program
My question is why base Class Sum FunCtion is not getting called by this code?
base A2 = new Program();
A2.Sum();
A method that is marked a override overwrites the complete implementation of its base-method. So if you create an instance of your derived class Program, this overriden method is called. However you may also call the base-implementation from within your derived method by using base.Sum()
public override void Sum()
{
base.Sum(); // now you see why base is a really bad name for your class
Console.WriteLine("SUM IN Program ");
}
Polymorphism changes the implementation of your subclass. Even if you upcast a subclass reference to its base type, you won't be able to access base class virtual method implementation, but the deepest implementation of the object inheritance.
In the other hand, a derived class can effectively access base class implementation using the base keyword:
public override void Sum()
{
// This calls base implementation.
base.Sum();
Console.WriteLine("SUM IN Program ");
}
Anyway, base will call the immediate base class' implementation. You won't be able to call an implementation above one level in the inheritance tree.
It is because you have overridden the base classes implementation. Virtual/Override says "Hey every time this method is called use the overridden method."
If you had marked the child class function with the new keyword, it would do what you describe. (Personally, I don't like using the new keyword, as most people don't understand the nuances of its implementation, but it performs the behavior you described. There are better alternatives).
Article describing new keyword.
Below code:
public class Program
{
static void Main(string[] args)
{
father f = new son(); Console.WriteLine(f.GetType());
f.show();
}
}
public class father
{
virtual public void show()
{
Console.WriteLine("father");
}
}
public class son : father
{
public override void show()
{
Console.WriteLine("son");
}
}
The result is 'son'.
If I modify the 'public override void show()' to 'public new void show()',the result is 'father'.
So I conclude below 'rules':
Use 'override', which function will be called is determined in run
time. The program will choose the right function according to the
real type of current object.(As above, the f's runtime type is son,
so it calls the son's show.)
Use 'new' modifier, which function will be called is determined when
it is compiled.The program will choose the object's declared type to
call its function.(As above, the f's declared type is father ,so
using 'new' modifier make the output to show 'father'.
All above are what I understand about polymorphism.Any misunderstanding and wrong?
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
Not really. The decision is still made at execution time, but the new method does not override the virtual method in the base class. This is most easily shown by extending your example somewhat:
using System;
class Base
{
public virtual void Foo()
{
Console.WriteLine("Base.Foo");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("Derived.Foo");
}
}
class MoreDerived : Derived
{
public new void Foo()
{
Console.WriteLine("MoreDerived.Foo");
}
}
class Test
{
static void Main()
{
Base x = new MoreDerived();
x.Foo(); // Prints Derived.Foo
}
}
Here, at compile time the decision is made to call the most overridden implementation of Base.Foo - if there were multiple Foo signatures, the decision about which signature to use would be taken, for example. Which implementation will be "the most overridden" is unknown at this point, of course.
At execution time, the CLR will find that most overridden implementation based on the actual type of the target object - which is MoreDerived. But MoreDerived.Foo doesn't override Base.Foo... whereas Derived.Foo does, so the implementation in Derived is the one which is actually executed.
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
This is slightly wrong. Using new means that this function does not override any functions of the base class. The function dispatch still happens at runtime, but this function is not considered. The difference would be clearer if you had Grandson or Daughter classes to test more.
yes it work like that only...your understanding is right..
But for second case when you use new intad of override it hide actual implementation i.e. parent class implementation
As the new keyword was used to define this method, the derived class method is not called—the base class method is called instead.
EXample from MSDN
// Define the base class
class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
// Define the derived classes
class ConvertibleCar : Car
{
public new virtual void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("A roof that opens up.");
}
}
class Minivan : Car
{
public override void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("Carries seven people.");
}
}
call to the class
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
output
Car object: YourApplication.Car
Four wheels and an engine.
----------
Car object: YourApplication.ConvertibleCar
Four wheels and an engine.
----------
Car object: YourApplication.Minivan
Four wheels and an engine.
Carries seven people.
----------
MSDN having good example of it : Knowing When to Use Override and New Keywords (C# Programming Guide)
A normal method is called by type of class and a virtual method is called by content of memory allocated to the object. Now keyword new hides the concept of polymorphic and just care for its type.
This question already has answers here:
C# constructor execution order
(7 answers)
Closed 5 years ago.
I was just reading Inheritance in C# in which i came across the Constructors and was written that constructors are executed in order of derivation. What does it mean?That base class constructor will be called first or Derived class.
A base class Constructor is called first.Refer to the following example
// Demonstrate when constructors are called.
using System;
// Create a base class.
class A {
public A() {
Console.WriteLine("Constructing A.");
}
}
// Create a class derived from A.
class B : A {
public B() {
Console.WriteLine("Constructing B.");
}
}
// Create a class derived from B.
class C : B {
public C() {
Console.WriteLine("Constructing C.");
}
}
class OrderOfConstruction {
static void Main() {
C c = new C();
}
}
The output from this program is shown here:
Constructing A.
Constructing B.
Constructing C.
The base class constructor will be called first. You can test this pretty easily yourself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DerivationTest
{
class Program
{
public class Thing
{
public Thing()
{
Console.WriteLine("Thing");
}
}
public class ThingChild : Thing
{
public ThingChild()
{
Console.WriteLine("ThingChild");
}
}
static void Main(string[] args)
{
var tc = new ThingChild();
Console.ReadLine();
}
}
}
Class constructors are called in the order implied by derivation, but it's important to note that in C#, field initializers (e.g. int foo=5) are run before the base class constructor, and thus run in the opposite order. This is primarily useful if the base constructor may cause virtual function which is overridden in the derived class to be called before the base constructor has completed. Such a function will see any variables that were initialized by field initializers as having been initialized.
VB.net, incidentally, runs all field initializers after the base class constructor completes, but before anything in the derived class constructor (other than the chain to the base constructor). This means that virtual methods have to be aware that field initializers may not have run, but also means that field initializers can make use of the object under constructions (which they cannot do in C#).
Incidentally, in VB.net, it's possible, though clunky, for a class to safely initialize fields with newly-created IDisposable instances (and ensure they will get disposed if the any part of the construction process throws an exception). In C#, one must refrain from using field initializers to create anything that cannot be safely abandoned if construction throws an exception, since there will be no way to access the partially-constructed object to clean it up.
using System;
class Parent
{
public Parent () {
Console.WriteLine("Hey Its Parent.");
}
}
class Derived : Parent
{
public Derived () {
Console.WriteLine("Hey Its Derived.");
}
}
class OrderOfExecution {
static void Main() {
Derived obj = new Derived();
}
}
The output from this program is shown here:
Hey Its Parent.
Hey Its Derived.
Constructor acts differently in Inheritance bit confusing for new Programmers. There are two concepts in execution of constructor
1. Calling
2. Execution
When you create a object of your derived class Named Derived the constructor first goes to Derived() then it goes to Parent() because of its calling.
Constructor calling is done from Bottom to Top but then you find it Executes Parent() first then Derived , that is because of its Execution.
Constructors Executed from Top to Bottom. That's why it print Parent first then Base while base constructor called first.