K
K
Kinhagen2018-09-15 20:22:51
OOP
Kinhagen, 2018-09-15 20:22:51

Upcast: Accessing base class methods with different access modifiers from derived class after Upcast?

Hello. I don't know how to insert the code, but here's an example question:
There is a base class with valid methods:
class X
{... fields/properties...
public int Aaa();
protected int Bbb();
private int Ccc();
...}
And there is a child class in which the upcast is made (also a couple of methods for example):
class Y : X
{... fields/properties...
public string Sss();
protected string www();
private string Ttt();
...
Y petya = new Y();
X man = petya; // upcast
}
Questions:
1. Does pet lose all his Sss, Www, Ttt methods when he becomes a man? (even public Sss?)
2. What methods of the parent class does petya, who has become a man, have access to? Those. what is allowed: male.Aaa()? man.Bbb()? man.ccc()? (I'm especially interested in protected Bbb, because man.Bbb() gives me an error)
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AnarchyMob, 2018-09-16
@Kinhagen

public methods can be called via cast:

if (мужчина is Y y)
{
    y.Sss();
}

or
or Access to protected methods is allowed only inside the class itself (if you add internal to the protected modifier, access extends to the assembly level), private methods are not virtual, they are not inherited. PS Well, you have identifiers ...

G
GavriKos, 2018-09-15
@GavriKos

Absolutely nothing will happen to the pet - it remains an instance of class Y, which has access to both its own methods and the methods of the parent.
But you can't access them through the "male" variable without casting to Y.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question