TypeScript function signature in abstract class doesn't need to match interface - oop

In the following example, interface IFoo declares a function signature requiring two number arguments. Abstract class BaseFoo implements this interface, but declares the function with a different signature. Finally, concrete class Foo extends BaseFoo and implements BaseFoo's version of the function declaration.
interface IFoo {
func(x: number ): number
}
abstract class BaseFoo implements IFoo {
abstract func(x: number): number
}
class Foo extends BaseFoo {
func() { return -1 } // Does not match interface func declaration
}
let foo: IFoo = new Foo() // Should not be able to instantiate a Foo as an IFoo
let y = foo.func() // Should not be able to call without an argument
console.log(y)
This contrived example illustrates something that happened in real life: I had an existing interface in a codebase. I updated one of it's function's signatures, with the expectation that the compiler would help me find all the classes who would need to be updated. But, no errors.
Why am I allowed to instantiate an abstract class with a function signature that doesn't match the interface?

Related

How to call an abstract method from a Class parameter in Kotlin?

Aim
Have a function Book, which takes one of three Letter classes as argument myClass and then calls 'genericMethod()' from the abstract class which Letter*() has inherited.
Issue
If I try Book(LetterA()).read() I get the following error:
Type mismatch. Required: Class<SampleClassArguments.Alphabet> Found: SampleClassArguments.LetterA
Does Kotlin have any way to achieve this result?
Code
#Test
fun readBookTest() {
Book(LetterA()).read() /*<--error here*/
}
class Book(val myClass: Class<Alphabet>) {
fun read() {
val letterClass = myClass.getConstructor().newInstance()
letterClass.genericMethod(myClass.name)
}
}
class LetterA(): Alphabet()
class LetterB(): Alphabet()
class LetterC(): Alphabet()
abstract class Alphabet {
fun genericMethod(className: String) {
println("The class is: $className")
}
}
You need to define the Class type as covariant with the out keyword so any of the child classes is an acceptable argument:
class Book(val myClass: Class<out Alphabet>)
And when you use it, you need to pass the actual Class, not an instance of the class. You can get the Class by calling ::class.java on the name of the class:
#Test
fun readBookTest() {
Book(LetterA::class.java).read()
}

Dart : Why should overriding method's parameter be "wider" than parent's one? (probably topic about Contravariant) Part2

https://dart.dev/guides/language/language-tour#extending-a-class
Argument types must be the same type as (or a supertype of) the
overridden method’s argument types. In the preceding example, the
contrast setter of SmartTelevision changes the argument type from int
to a supertype, num.
I was looking at the above explanation and wondering why the arguments of subtype member methods need to be defined more "widely"(generally) than the original class's one.
https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Function_types
class AnimalShelter {
Animal getAnimalForAdoption() {
// ...
}
void putAnimal(Animal animal) {
//...
}
}
class CatShelter extends AnimalShelter {
//↓ Definitions that are desirable in the commentary
void putAnimal(Object animal) {
// ...
}
//↓Definitions that are not desirable in the commentary
void putAnimal(Cat animal) {
// ...
}
//I can't understand why this definition is risky.
//What specific problems can occur?
}
I think this wikipedia sample code is very easy to understand, so what kind of specific problem (fault) can occur if the argument of the member method of the subtype is defined as a more "narrower"(specific) type?
Even if it is explained in natural language, it will be abstract after all, so it would be very helpful if you could give me a complete working code and an explanation using it.
Let's consider an example where you have a class hierarchy:
Animal
/ \
Mammal Reptile
/ \
Dog Cat
with superclasses (wider types) above subclasses (narrower types).
Now suppose you have classes:
class Base {
void takeObject(Mammal mammal) {
// ...
}
Mammal returnObject() {
// ...
}
}
class Derived extends Base {
// ...
}
The public members of a class specify an interface: a contract to the callers. In this case, the Base class advertises a takeObject method that accepts any Mammal argument. Every instance of a Base class thus is expected to conform to this interface.
Following the Liskov substitution principle, because Derived extends Base, a Derived instance is a Base, and therefore it too must conform to that same Base class interface: its takeObject method also must accept any Mammal argument.
If Derived overrode takeObject to accept only Dog arguments:
class Derived extends Base {
#override
void takeObject(Dog mammal) { // ERROR
// ...
}
}
that would violate the contract from the Base class's interface. Derived's override of takeObject could be invoked with a Cat argument, which should be allowed according to the interface declared by Base. Since this is unsafe, Dart's static type system normally prevents you from doing that. (An exception is if you add the covariant keyword to disable type-safety and indicate that you personally guarantee that Derived.takeObject will never be called with any Mammals that aren't Dogs. If that claim is wrong, you will end up with a runtime error.)
Note that it'd be okay if Derived overrode takeObject to accept an Animal argument instead:
class Derived extends Base {
#override
void takeObject(Animal mammal) { // OK
// ...
}
}
because that would still conform to the contract of Base.takeObject: it's safe to call Derived.takeObject with any Mammal since all Mammals are also Animals.
Note that the behavior for return values is the opposite: it's okay for an overridden method to return a narrower type, but returning a wider type would violate the contract of the Base interface. For example:
class Derived extends Base {
#override
Dog returnObject() { // OK, a `Dog` is a `Mammal`, as required by `Base`
// ...
}
}
but:
class Derived extends Base {
#override
Animal returnObject() { // ERROR: Could return a `Reptile`, which is not a `Mammal`
// ...
}
}
void main(){
Animal a1 = Animal();
Cat c1 = Cat();
Dog d1 = Dog();
AnimalCage ac1 = AnimalCage();
CatCage cc1 = CatCage();
AnimalCage ac2 = CatCage();
ac2.setAnimal(d1);
//cc1.setAnimal(d1);
}
class AnimalCage{
Animal? _animal;
void setAnimal(Animal animal){
print('animals setter');
_animal = animal;
}
}
class CatCage extends AnimalCage{
Cat? _cat;
#override
void setAnimal(covariant Cat animal){
print('cats setter');
_cat = animal;
/*
if(animal is Cat){
_cat = animal;
}else{
print('$animal is not Cat!');
}
*/
}
}
class Animal {}
class Cat extends Animal{}
class Dog extends Animal{}
Unhandled Exception: type 'Dog' is not a subtype of type 'Cat' of 'animal'
In the above code, even if the setAnimal method receives a Dog instance, a compile error does not occur and a runtime error occurs, so making the parameter the same type as the superclass's one and checking the type inside the method is necessary.

How to mock a local variable initialized with the member variable

I have two classes Class A and Class SRD (Sample classes for understanding the problem. Real classes are different). Both classes have same Function(method1) with same arguments. Both are not derived from different Classes.
Class SRD is the member of Class A. a function in Class A creates a new object for SRD and calls method1(). It should call the mock function. but it calls the actual implementation
I have Written mock classes for both the classes and defined the mock method in both the classes and Wrote EXPECT_CALL in TEST function
class A{
private:
SRD* srd;
public :
bool Method1();
bool MethodX();
SRD* getsrd() {return srd;}
};
bool A :: MethodX()
{
srd.Method1(); // Not Calling Mock Method - Calling Actual
//Implementation
}
bool A::Method1()
{
....
}
class SRD{
public:
bool Method1();
};
class MockSRD : public SRD{
MOCK_METHOD0(Method1, bool())
};
class MockA : public MockA{
MOCK_METHOD0(Method1, bool())
};
bool SRD::Method1()
{
....
}
class TestA : public A {};
TEST_F(TestA, test1)
{
MockSRD srd;
EXPECT_CALL(srd, Method1())
.Times(testing::AnyNumber())
.WillRepeatedly(Return(true));
srd.Method1() //Working fine - Caling mock Method;
MethodX()
}
When i call s1.Method1(), It should call the mock method. how should i do that ?
I don't want to change the production code.
Thanks for taking time to respond the Question . #Chris Oslen & #sklott
I forgot to make the base class method to Virtual. Its worked fine when i change the base class methods

"same JVM signature" implementing kotlin interface containing getter method

interface MyInterface {
fun getTheString(): String
}
class MyClass(var theString: String) : MyInterface {
...
}
normally when I have a variable in the constructor for a class, it creates a getter and setter for that variable. In MyClass, the methods getTheString() and setTheString(String) exist when not implementing MyInterface.
When MyClass implements MyInterface, I get the error:
Accidental override: The following declarations have the same JVM signature (getTheString()Ljava/lang/String;):
public final fun (): String defined in MyClass
public abstract fun getTheString(): String defined in MyClass
I also have the error: Class 'MyClass' is not abstract and does not implement abstract member public abstract fun getTheString(): String defined in MyInterface.
So I have a few questions:
Why are 2 getter methods getting generated with the same JVM signature when implementing the interface versus one getter method getting generated without implementing the interface?
Why is it complaining I haven't implemented a getTheString() method when this method is automatically generated by kotlin?
How can I get the getter generated by the variable to become the implementation of the method in the interface?
If the interface is indeed in Kotlin, and you can change it, it should be
interface MyInterface {
val theString: String
}
in the first place. Java will still see getTheString(), but it's nicer to both implement and use in Kotlin.
Otherwise a good option is
class MyClass(#set:JvmName("setTheString") var _theString: String) : MyInterface {
override fun getTheString() = _theString
}
Unfortunately, it still has a duplicate getter, and you can't make only the getter private. Or
class MyClass(private var _theString: String) : MyInterface {
override fun getTheString() = _theString
fun setTheString(value: String) {
_theString = value
}
}
Note that if the interface is in Java, getTheString() will be visible to Kotlin as a property.
See issues https://youtrack.jetbrains.com/issue/KT-6653 and https://youtrack.jetbrains.com/issue/KT-19444 on the Kotlin bug tracker.

OOP - How to create an interface in Reason

Let's say I have the following abstractProductA class with a public method called methodA :
class abstractProductA = {
pub methodA => "name";
};
I would like to create an interface that says function methodA should always return a string. Something similar to
interface abstractProductA {
abstractProductA(): string
}
only in reason, and then have class implement it. Any suggestions are more than welcome. Thank you
What you're really asking for it seems is how to define and use an abstract class, which is called a virtual class in OCaml/Reason:
class virtual virtualProductA = {
pub virtual methodA: string;
};
class abstractProductA = {
inherit virtualProductA;
pub methodA = "name";
};
An interface is more for consumers to abstract away an implementation, and while a virtual class can be used as an interface by itself, since OCaml/Reason objects are structurally typed you can also just specify the object type you need. And of course you can bind it to a name if you like:
type interfaceA = {.
methodA : string
};
let f (p: interfaceA) => Js.log p#methodA;
f (new abstractProductA);