Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling child class method from parent

Is it possible for the a.doStuff() method to print "B did stuff" without editing the A class? If so, how would I do that?

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();

        a.doStuff();
        b.doStuff();

        Console.ReadLine();
    }
}

class A
{
    public void doStuff()
    {
        Console.WriteLine("A did stuff");
    }
}

class B : A
{
    public void doStuff()
    {
        Console.WriteLine("B did stuff");
    }
}

I'm modding a steam game, Terraria. And I don't want to decompile and recompile it all because that will screw with steam. My program 'injects' into Terraria via XNA. I can use the update() and draw() methods from XNA to mod some things. But it's pretty limited. I wan't to override base methods to mod more things (worldgen for example).

like image 693
user1178494 Avatar asked Jan 30 '12 17:01

user1178494


People also ask

Can a parent class call child class method?

Why we can't call child specific methods with the help of parent reference on child object in Java? Imagine that your child class is inheriting the parent class. Then the child class can define it's own methods, that are not defined in the parent class and not inherited by the child class.

Can a parent class access child class methods Python?

This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.

Can we call child class method from parent object in Java?

we can called the overridden methods of child class with parent class reference we can not call the direct child class methods from parent class reference.

How do you call a parent class method?

Method 1: Use Self-Reference to Access Parent Method The child inherits all methods and attributes from the parent. Thus, to access the parent method, you can use the self reference passed as a child method's argument. For example, you can call self.


2 Answers

Yes, if you declare doStuff as virtual in A and then override in B.

class A
{
    public virtual void doStuff()
    {
        Console.WriteLine("A did stuff");
    }
}

class B : A
{
    public override void doStuff()
    {
        Console.WriteLine("B did stuff");
    }
}
like image 179
Aliostad Avatar answered Oct 01 '22 12:10

Aliostad


Since B is effectively A through inheritance and the method is overloaded.

A a = new B();
a.doStuff();
like image 45
mdprotacio Avatar answered Oct 01 '22 11:10

mdprotacio