class A
{
}
class B : A
{
}
I know that B b = new A(); is not possible, but what is the explanation behind it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
By deriving from
A, you specify that instances ofBare not onlyB, they’reAalso. This is called inheritance in OOP. The power of inheritance is in being able to abstract away general properties/behaviour to a common class and then derive specialized classes from it. The specialized classes can change existing functionality (called overriding) or add new functionality.However, inheritance works only in one direction, not both. Objects of class
Acannot be treated asBbecause B may (and often does!) contain more functionality thanA. Or, in other words,Bis more specific whileAis more general.Therefore, you can do
A a = new B();but notB b = new A();