Derived Class Cannot refer to parent class - c#-3.0

class Program
{
static void Main(string[] args)
{
Father objFather = new Son(); //Ok compiles
Son objSon1 = new Father(); //Comile time error : Cannot implicitly convert type
Son objSon = (Son)new Father(); //Run time error
Console.ReadLine();
}
}
class Father
{
public void Read()
{
}
}
class Daughter:Father
{
}
class Son:Father
{
}
Can anybody Explain why it is? And what is happening in memory?

You seem to misunderstand inheritance.
Every Daughter and every Son is a Father. That's why you can safely assign both to a Father variable. A subclass can't remove attributes/methods only add them, that's why it's sure it's always working.
But when you have an instance of Father and want to assign it to a Son variable, you can't be sure that the instance is a Son and actually has all the properties needed. The Father instance could as well contain a Daughter which is not compatible to Son. That's why the compiler can't implicitly convert them but you as a programmer can explicitly do it.

Related

Dart - Way to access a inherited static property from a parent class method

In PHP there is a way of accessing a static property value that is defined/overridden on an inheritor.
e.g.
class Foo {
public static $name='Foo';
public function who(){
echo static::$name;//the static operator
}
}
class Bar extends Foo {
public static $name='Bar';
}
$bar = new Bar();
$bar->who();
//Prints "Bar";
Is there ANY way of doing the exact same thing in Dart language?
Addressing comments:
About making it instance prop/method: There's a reason for the existence of static properties and methods and it's not having to create a new instance of the object to access a value or functionality that is not mutable.
Yes, but that's not how you are using it. Your use case is to invoke the method on an object, and therefore you really want an instance method. Now, some languages automatically allow invoking class methods as instance methods, and I see two choices for a language that offers that ability:
Statically transform fooInstance.classMethod() to ClassFoo.classMethod() based on the declared type (not the runtime type) of the object. This is what Java and C++ do.
Implicitly generate virtual instance methods that call the class method. This would allow fooInstance.classMethod() to invoke the appropriate method based on the runtime type of the object. For example, given:
class Foo {
static void f() => print('Foo.f');
}
You instead could write:
class Foo {
static void classMethod() => print('Foo.f');
final instanceMethod = classMethod;
}
and then you either could call Foo.classMethod() or Foo().instanceMethod() and do the same thing.
In either case, it's syntactic sugar and therefore isn't anything that you couldn't do yourself by being more verbose.
About the "meaning of static" and "only work because they allow invoking class methods as instance methods" : That affirmation is actually wrong. In the case of PHP, as per the example above, the Language is providing a way to access the TYPE of the class calling the method in the inheritance chain. A(methodA) >B > C. When C calls methodA, PHP allows you to know that the class type you're in is indeed C, but there's no object instance attached to it. the word "static" there is a replacement for the caller class type itself
All of that is still known at compilation time. That C derives from B derives from A is statically known, so when you try to invoke C.methodA, the compiler knows that it needs to look for methodA in B and then in A. There's no dynamic dispatch that occurs at runtime; that is still compile-time syntactic sugar. That is, if you wanted, you could explicitly write:
class A {
static void methodA() {}
}
class B extends A {
static void methodA() => A.methodA();
}
class C extends B {
static void methodA() => B.methodA();
}
Anyway, in your example, you could write:
class Foo {
static String name = 'Foo';
String get nameFromInstance => name;
void who() {
print(nameFromInstance);
}
}
class Bar extends Foo {
static String name = 'Bar';
#override
String get nameFromInstance => name;
}
void main() {
var bar = Bar();
bar.who(); // Prints: Bar
}

Use a method of a class in another class

I have 2 kotlin files, each contains a class, first.kt contains class First and second.kt contains class Second.
In First, I have a method named "Create".
I wanna use the Create method in Second, but I don't want to create an instance of First.
I'm new in kotlin, I want something like static methods in c#
You can use companion object for that. Then import the method from First like this
First.kt
class First {
companion object {
fun create() {
println("Hello from create")
}
}
}
Second.kt
import First.Companion.create
class Second {
fun getData() {
create()
}
}

String Constructor not working in unity c#

Salutations, this'll be brief.
So, I tried to change the name of one the hero struct in my game, but it doesn't update, neither in the inspector nor in the de facto code.
I can call the constructor just fine, and if I print the heroname before and after (in the constructor), it tells me the new name. However, It does not change.
Here is the (simplified) code:
//This already has a name in the inspector that I want to override
public List<TroopStat> PlayerHeroStats = new List<TroopStat>();
void Start () {
PlayerHeroStats[0].ChangeTroopType();
}
[System.Serializable]
public struct TroopStat {
public string nameOfTroop;
public void ChangeTroopType() {
nameOfTroop = "Blabla";
}
}
Any ideas?
Structs are value types. You need to assign a new struct or use class instead.
This should work:
void Start () {
TroopStat stat = PlayerHeroStats[0];
stat.ChangeTroopType();
PlayerHeroStats[0] = stat;
}
Or make the TroopStat a class.
You can read more about it here.

Why does Eclipse Compiler lose fixed type parameter?

I struggled to find a proper title for this question because the phenomenon I observed is very strange. Hence I skip explaining my problem literally and instead show you some (hopefully) self-describing code. Consider the following parameterized class:
public class GenericOptional<T> {
public GenericOptional(T someValue) {}
public T getValue() { return null; }
public Optional<String> getOptionalString() { return Optional.empty(); }
}
What I like to emphasize is that the return type Optional<String> of the method getOptionalString() does not depend on the type-parameter T.
Now have a look at the following code, which gets compiled inside Eclipse Luna 4.4.2 using Java 8u45:
public static void main(String[] args) {
Object obj = new GenericOptional<>(Boolean.TRUE);
GenericOptional go = (GenericOptional) obj;
Optional os = go.getOptionalString();
}
The local variable os has the type Optional without the type-parameter String! The Eclipse compiler has lost the information about the fixed type-parameter. Does anyone know why?
Now look at a second code example:
public static void main(String[] args) {
Object obj = new GenericOptional<>(Boolean.TRUE);
GenericOptional<?> go = (GenericOptional) obj;
Optional<String> os = go.getOptionalString();
}
By declaring the local variable go as GenericOptional<?> the return type of the method getOptionalString() now is Optional<String> as expected.
May anyone explain this behavior?
You are facing the behavior of raw types. When you are using a raw type, Generics are effectively turned off completely, regardless of whether there is a connection between the generic signature of the member and the type parameter of the class.
The reasoning behind this is that raw types are a feature for backward compatibility with pre-Generics code only. So either you have Generics or your don’t.
If the Generic method does not depend on the actual type parameter of the class, the problem is easy to fix:
GenericOptional<?> go = (GenericOptional<?>) obj;
Optional<String> os = go.getOptionalString();
Using <?> implies “I don’t know the actual type parameter and I don’t care but I’m using Generic type checking”.
It's not about Eclipse or anything, but about raw types.
Let's review this snippet:
public static void main(String[] args) {
Object obj = new GenericOptional<>(Boolean.TRUE);
GenericOptional go = (GenericOptional) obj;
Optional os = go.getOptionalString();
}
Here, you're creating a raw instance of GenericOptional, which means that the type-parameter information will be completely turned off. So, instantiating a raw GenericOptional means that the instance will expose the methods as following:
public class GenericOptional {
public GenericOptional(Object someValue) {}
public Object getValue() { return null; }
public Optional getOptionalString() { return Optional.empty(); }
}
However, if we now review the second snippet
public static void main(String[] args) {
Object obj = new GenericOptional<>(Boolean.TRUE);
GenericOptional<?> go = (GenericOptional) obj;
Optional<String> os = go.getOptionalString();
}
we can see that you're making a generic instance of GenericOptional. Even it's type-parameter is <?>, the compiler will not turn-off caring about type-parameters, so the instance will expose the getOptionalString() method parameterized, like this:
public Optional<String> getOptionalString() { return Optional.empty(); }

setting initial variable for base class from inherited class

I am a little rusty with C++ and am getting bogged down with what is probably a simple question, so apologies in advance.
I have created a child class from an existing library class and cannot work out how to set up an initial state for one of the base class functions.
Basically I have taken the sfml circleshape class and added a little of my own, but I would like to set the origin for all derived objects as a fixed number.
The base class takes 'name of class'.setOrigin(x,y) which is straightforward, but I want to know how to set this as a standard figure in all derived class instances. (basically my child class is called Ball and I have class Ball ball1, ball2 etc
This may make it clear what I have at the moment:
//derived class-----------------------------------------
class Ball : public sf::CircleShape
{
private:
int horiz,vert,rate,radius;
public:
void setHoriz(int hin)
{
horiz=hin;
}
int getHoriz(int hout)
{
hout=horiz;
return(hout);
}
void setVert(int vin)
{
vert=vin;
}
int getVert(int vout)
{
vout=vert;
return(vout);
}
//-----------------------------------------------
void setRate(int in)
{
rate=in;
}
int getRate(int out)
{
out=rate;
return(out);
}
//-----------------------------------------
};
So any advice on how to insert ' CircleShape.setOrigin ' into the Ball class would be appreciated. Thanks