How to check if class is based on other abstract class [duplicate] - oop

This question already has an answer here:
Dart see if Instance of type inherits from other type
(1 answer)
Closed 1 year ago.
How can I check if my object of type A extends type B when the instance only extending B but is of type C.
For example:
abstract class A {
}
abstract class B extends A {
}
class C extends B {
}
A myA = C();
I want to test if myA is extends B class (which it is in the example).
Tested the following
if (myA.runtimeType is B) // return false
if (myA.runtimeType == B) // return false
if (myA == B) // return false

You need to remove the .runtimeType and use the is operator like this
if (myA is B) // return true
Than the statement will return true like you want if myA is extends B even if it is not directly instance of B.

Related

Is it possible to bind a class member in kodein?

There is 2 classes:
A - base class
B - class of member of A
with implementation something like this:
class A {
val b : B = B()
}
class B
Problem
Is it possible to create a binding for b to hide redundant info about b source in common classes?
Kodein declaration:
override val kodein by Kodein.lazy {
bind<A>() with singleton { A() }
bind<B>() with "a.b some impl???"
}
Usecase
class Usecase(kodein : Kodein){
val b : B = kodein.instance()
}
Very simple :
bind<B>() with provider { instance<A>().b }
The provider binding is the simplest one : it will call the provided function everytime.
The function itself runs inside a Kodein context, hence the use of the instance function.

How could I somehow find out in which constructor I am in a class hierarchy?

Let's say I have 3 TypeScript classes like this:
class A {
A1 = "";
A2 = 4;
constructor() {}
}
class B extends A {
B1 = "424";
constructor() {
super();
}
}
class C extends B {
C1 = false;
constructor() {
super();
}
}
When I create an instance of A, B or C, I need to run some routines which loop through the properties of the object. Because of the design of TypeScript's constructor and field initializer logic, for example when I construct a B instance, at the end of the A constructor I don't have the B properties in my object yet. This leads me to ensure that this "field-looping stuff" initialization logic is called at and only at the bottom of the constructor chain.
So this led me to the question: when coding for example B's constructor, can I check somehow wether I am constructing a B instance, or is it a C? In the latter, I would skip the initialization logic and leave it the C constructor.
I hope the question and the motivation is understandable.
PS: I know that if I don't use field initializers anywhere, but initialize every field in the constructor BEFORE calling super(), then the problem goes away because at the top most level constructor in the end I would have all the fields needed. However, I like the syntax of field initializers, in such cases it produces a more readable, smaller code.
when coding for example B's constructor, can I check somehow wether I am constructing a B instance, or is it a C? In the latter, I would skip the initialization logic and leave it the C constructor
You can use the constructor property.
Sample:
class A {
A1 = "";
A2 = 4;
constructor() {
if (this.constructor == A) this.loopAfterInit();
}
loopAfterInit(){console.log(Object.keys(this))}
}
class B extends A {
B1 = "424";
constructor() {
super();
if (this.constructor == B) this.loopAfterInit();
}
}
class C extends B {
C1 = false;
constructor() {
super();
if (this.constructor == C) this.loopAfterInit();
}
}
new A(); // A props logged
new B(); // A,B props logged
new C(); // A,B,C props logged

superclass accesing methods of a sublass in oop

I was wondering, is it possible that a superclass to access the methods of a inherited subclass, like for example in Java?
I know that a subclass can override and even implements, in case of abstract classes, the methods of the superclass, but the question mentioned above is possible?
Thanks
Example in c#.. in superclass make abstract method, which is implemented in derived class
public abstract class SuperCLass
{
public void CallSubMethod()
{
Test(); // calls method in derived class
}
public abstract void Test();
}
public class SubClas : SuperCLass
{
public override void Test()
{
// code here
}
}
Java, PHP, Ruby, Python, C# (and so on) methods are always virtual, so, no matter what, when you override a method in a subclass, this version will be called:
public class SuperClass {
public void someMethod() {
otherMethod();
}
public void otherMethod() {
System.out.println("Super");
}
}
public class SubClass extends SuperClass {
public void otherMethod() {
System.out.println("Sub");
}
}
SubClass o1 = new SubClass();
o1.someMethod(); // Outputs: Sub
SuperClass o2 = new SubClass();
o2.someMethod(); // Also outputs: Sub
So, you not just CAN access your subclass method, you HAVE TO.
Just for comparison, in C++, for example, things work different. If you don't declare a method as virtual, you can't override it.
I' ll try to explain as they explained to me at university.
You have a reference:
Object o = new Object()
His static type(ST) is Object : this is his own type and never changes.
His dynamic type(DT) is also Object(in this case): the reference point to an object of type Object, but it can change.
for example if i write :
Object o = new String("abc") // now his ST == Object but the DT == String
That being said:
Upcasting is always permitted: consider two references s and r. the assignment s=r compile and execute always if ST(r) <= ST(s) (the static type of r is, in the hierarchi, less or equals to the static type of s)
for example:
class A { }
class B extends A { }
...
A a = new A(); B b = new B();
a = b // OK, upcast
Downcasting: at compile-time it is always legal to downcast from a type X to a type Y if X and Y belong to hierarchy.
Consider the reference s. I want to cast s to a type C, so if C <= TS(s) it will always compile if I do the cast as : C r = (C)s
for example:
class A { }
class B extends A { }
class C extends A { }
...
A a = new A(); B b = new B();
C c = new C();
...
b = c // ILLEGAL
b = (B)a // OK at compile-time but maybe at run-time it is not!
When we run our application if the downcast fails, Java raise an Exception.
Otherwise it success.
To downcast correctly:
consider a reference ref and we want to cast to a type C. So a downcast will success if DT(ref) <= C <= ST(ref) .
And the downcast will be obtained as: C ref2 = (C)ref
for example:
// I suggest to write the hierarchy in a piece of paper and
// try the rules before coding.
class A { }
class B extends A { }
class C extends A { }
class D extends B { }
...
A a = new A(); B b = new B();
C c = new C(); D d = new D();
A r = new B();
A s = new D();
a = b; // OK, upcast
a = d; // OK, upcast
/* b = c; */ // ILLEGAL
b = (B)r; // OK, downcast
d = (D)r; // downcast: it compiles, but fails at run-time
d = (D)s; // OK, downcast
/* b = s; */ // ILLEGAL
/* d = (D)c; */ // ILLEGAL
b = (B)s; // OK, downcast
b = (D)s; // OK, downcast
PS: please forgive if I made some mistake but I wrote a bit in a hurry.
In Java, It's not possible, and I think what you are asking would go against OOP.

OOP question involving the best way to reference a base class protected variable without having to typecast every-time it is used

I have a quick OOP question and would like to see how others would approach this particular situation. Here it goes:
Class A (base class) -> Class B (extends Class A)
Class C (base class) -> Class D (extends Class C)
Simple so far right? Now, Class A can receive an instance of Class C through its constructor. Likewise, Class B can receive an instance of either class C or Class D through its constructor. Here is a quick snippet of code:
Class A
{
protected var _data:C;
public function A( data:C )
{
_data = data;
}
}
Class B extends A
{
public function B( data:D )
{
super( data );
}
}
Class C
{
public var someVar:String; // Using public for example so I don't need to write an mutator or accessor
public function C() { } // empty constructor for example
}
Class D extends C
{
public var someVar2:String; // Using public for example so I don't need to write an mutator or accessor
public function D() { super(); } // empty constructor for example
}
So, let's say that I am using class B. Since _data was defined as a protected var in Class A as type C, I will need to typecast my _data variable to type D in class B every time I want to use it. I would really like to avoid this if possible. I'm sure there is a pattern for this, but don't know what it is. For now, i'm solving the problem by doing the following:
Class B extends A
{
private var _data2:D;
public function B( data:D )
{
super( data );
_data2 = data;
}
}
Now, in class B, I can use _data2 instead of typecasting _data to type D every-time I want to use it. I think there might be a cleaner solution that others have used. Thoughts?
I think B doesn't take C or D... in order for it to do what you wrote it should be
public function B( data:C )
{
super( data );
}
At least as far as I used to know :)
I doubt you can use a downwards inheritance in your case.
As for the pattern, the best one to use in situations like these is Polymorphism. Alternatively, depending on language, you can use interfaces. Or if languages allow it, even a combination of conventional code and templates.
Most modern OO languages support covariant of return type, that is: an overriding method can have a return type that is a subclass of the return type in the original (overridden) method.
Thus, the trick is to define a getter method in A that will return C, and then have B override it, such that it returns D. For this to work the variable _data is immutable: it is initialized at construction time, and from that point it does not change its value.
Class A {
private var _data:C;
public function A(data:C) {
_data = data;
}
public function getData() : C {
return _data;
}
// No function that takes a C value and assigns it to _data!
}
Class B extends A {
public function B(data:D) {
super(data);
}
public function getData() : D { // Override and change return type
return (D) super.getData(); // Downcast only once.
}
}
This how I usually write it in Java:
public class A {
private final C data;
public A(C data) { this.data = data; }
public C getData() { return data; }
}
public class B extends A {
public B(D data) { super(data); }
#Override
public D getData() { return (D) super.getData(); }
}

Is there any programming language in which you can override a method of 2 classes up?

For example, if you have class A, class B inheriting A, and class C inheriting B, is there any programming language in which class C can override a method of class A, even if class B don't override it?
class A {
method() {}
}
class B extends A{
}
class C extends B {
//override method from A
method(){}
}
AFAIK you can do this in most (if not all) OO languages, e.g. in Java and C++ for sure.
yes , It is very general case, Java does it.
This ruby code does exactly what you want:
class A
def hello
puts "hello from class A"
end
end
class B < A
end
class C < B
def hello
puts "hello from C"
end
end
B.new.hello
C.new.hello
Once executed you will have the following output:
hello from class A
hello from C
C# for one
public class A
{
virtual public int retval(int x)
{
return x;
}
}
public class B : A
{
}
public class C : B
{
public override int retval(int x)
{
return 3;
}
}
class Program
{
static void Main(string[] args)
{
A a = new C();
Console.WriteLine(a.retval(2).ToString());
}
}
I think most common languages will allow that without difficulty if all modules are recompiled. There is a gotcha in some (including C# and vb.net) if an override is added to a mid-level class which didn't have one when a child method was compiled. In that scenario, if the child classes are not recompiled, calls to their parent methods may bypass the mid-level classes (since those mid-level classes didn't have overrides when the child passes were compiled).