Java Inheritance Constraints - c#

I am trying to port some code I wrote in C# to Java, but do not know all of the Java syntax yet. I also have no idea what this type of thing is called, so it is harder to search..I am calling it "inheritance constraints."
Basically, is there a java equivalent to this C# code:
public abstract class MyObj<T> where T : MyObj<T>, new()
{
}
Thanks.
Edit:
Is there any way to do this:
public abstract class MyObj<T extends MyObj<T>> {
public abstract String GetName();
public virtual void Test() {
T t = new T(); // Somehow instantiate T to call GetName()?
String name = t.GetName();
}
}

Not quite. There's this:
public abstract class MyObj<T extends MyObj<T>>
but there's no equivalent to the new() constraint.
EDIT: To create an instance of T, you'll need the appropriate Class<T> - otherwise type erasure will byte you.
Typically you'd add this as a constructor parameter:
public MyObj(Class<T> clazz) {
// This can throw all kinds of things, which you need to catch here or
// propagate.
T t = clazz.newInstance();
}

Judging by your comment above, you're looking for the following construct:
An interface with which you will interact with MyObj objects in code... you will be calling the test() method (standard style in Java is camelcase methods, capitalized classes/interfaces)
public interface IMyObj {
public void test();
}
You will want the abstract superclass... for the example that you've chosen, you don't NEED to specify any genericism, although you absolutely can if the actual implementation is more reliant on type safety... this class should implement the IMyObj interface:
public abstract class MyObj implements IMyObj {
String name;
public abstract String getName();
public void test() {
name = getName();
}
}
From here you would write your subclasses to MyObj...
public class MySubObj1 extends MyObj {
public String getName() { return "MySubObj1"; }
}
public class MySubObj2 extends MyObj {
public String getName() { return "MySubObj2"; }
}
Then you safely and correctly use the following snippet in another class:
IMyObj obj = new MySubObj1();
obj.test();
The key is that you use interfaces to hide the implementation, and use abstract classes to hold common code that subclasses will utilize in their implementations.
Hope this helps!

Related

Creating an object with the interface name vs class name in C# [duplicate]

I have seen an Interface instance being generated from a class many times. Why do we use interface this way? An interface instance is created only itself with the help of the derived class and we can access only these interface members through this instance. How does this give an advantage? I'm so confused.
interface IPrint
{
void Print();
}
class Sample : IPrint
{
public void Print()
{
Console.WriteLine("Print...");
}
public void Sample()
{
Console.WriteLine("Sample...");
}
}
class Program
{
static void Main(string[] args)
{
IPrint print = new Sample();
print.Print();
}
}
Interfaces define that a class MUST be able to do something. This means that you know the object being worked on will do what you want to be able to do. It allows you greater freedom and is one of the advantages of OOP. This is a deep topic but a very basic example would be this:
public interface IAnimal
{
string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "Woof, woof";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "Meow";
}
}
public class Parrot : IAnimal
{
public string Speak()
{
return "Sqwark!";
}
}
Then you could use any animal you like!
class Program
{
static void Main(string[] args)
{
// Writes Woof, Woof
IAnimal animal = new Dog();
Console.WriteLine(animal.Speak());
// Now writes Meow
animal = new Cat();
Console.WriteLine(animal.Speak());
// Now writes Sqwark etc
animal = new Parrot();
Console.WriteLine(animal.Speak());
}
}
This also allows you to then get into things like Inversion Of Control where you would take an item in like this and you could pass a dog, cat or parrot and the method would always work, not knowing or caring which animal it was:
public void ShoutLoud(IAnimal animal)
{
MessageBox.Show("Shout " + animal.Speak());
}
This then makes ShoutLoud unit testable because you could use a mock object rather than a real animal. It basically makes your code flexible and dynamic rather than rigid and tightly coupled.
Also, expanding on Matthew's question. In C# you can only inherit from one base class but you can have multiple interfaces. So, you could have:
public class Dog : IAnimal, IMammal, ICarnivor
This allows you to have small interfaces (recommended) that then allow you to build up so giving maximum control over what an item can / must do.
Using an interface this way gives you the ability to create methods that use standard template of the interface. So here you might have many classes of printer that all inherit from IPrinter
class SamsungPrinter : IPrinter
{
// Stuff and interface members.
}
class SonyPrinter : IPrinter
{
// Stuff and interface members.
}
interface IPrinter
{
void Print();
}
So for each type SamsungPrinter, SonyPrinter, etc. you can pre-process using something like
public static void PreProcessAndPrint(IPrinter printer)
{
// Do pre-processing or something.
printer.Print();
}
You know from inheriting from IPrinter and using that type in the method parameters that you can always safely use the Print method on what ever object is passed.
Of course there are many other uses for using interfaces. One example of their use is in design patterns, in particular the Factory and Strategy patterns. The description of which and examples can be found here.
I hope this helps.
But how does this differ from, for example, using a base class with virtual methods?
You are all in the assumption that one programmer or one program writes the interface and the classes, but this doesn't always have to be this way.
Maybe you have a complete finished program that works with animals and you have this worked out using:
public abstract class Animal { public abstract string Speak(); }
And then some day you download some awesome DLL from nuget that shows pictures for animals. The class library contains a contract - interface - 'IAnimal':
namespace AwesomeAnimalLibrary
{
public interface IAnimal
{
string AnimalName;
}
}
The class library also maybe contains :
namespace AwesomeAnimalLibrary
{
public class AnimalPhotos
{
[Byte] GetPhotos(IAnimal animal);
}
}
What could you do now ? Your bas class Animal can implement the AwesomeAnimalLibrary IAnimal interface and that's it.
Don't assume that other people will use you abstract base classes but work together using interface contracts.
Interface can not have instance because interface implements only signatures of properties or methods. Interface is just a pointer to an instance of some class:
interface IExample
{
// method signature
void MyMethod();
}
public class MyClass : IExample
{
// method implementation
public void MyMethod()
{
ConsoleWriteline("This is my method");
}
}
// interface pointing to instance of class
IExample ie = new MyClass();
ie.MyMethod();

How to require an implementation of an abstract class in C#?

I want to build a class that would have a property, in which there is an instance of a class, which implements an abstract class. Here's and example.
public class MyClass {
public MyDerivedClassA derived;
public void mainClassUtility () {
derived.foo();
}
}
public abstract class MyAbstractBaseClass {
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass {
public override void foo(){
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
return;
}
}
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use. There will be many implementations of the abstract class and depending on the current state of the program, MyClass might be using different implementations of the ABC. I want to write the program in a way, that no matter what implementation of the ABC is currently being used, there is a way to call it's methods by MyClass. What would be the best solution to this problem?
Unless I'm misunderstanding the question, you're pretty much there. Have MyClass expect a property of the abstract base class and you should be all set.
using System;
public class Program
{
public static void Main()
{
var myClassOne = new MyClass(new MyDerivedClassA());
var myClassTwo = new MyClass(new MyDerivedClassB());
myClassOne.mainClassUtility();
myClassTwo.mainClassUtility();
}
public class MyClass
{
public MyAbstractBaseClass Derived;
public MyClass(MyAbstractBaseClass derived)
{
Derived = derived;
}
public void mainClassUtility ()
{
Derived.foo();
}
}
public abstract class MyAbstractBaseClass
{
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassA");
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassB");
return;
}
}
}
How to require an implementation of an abstract class in C#?
You can not instantiate a abstract class - and thus can not use it for most cases. Except as variable/argument/generic type argument. You need to make a concrete (non-abstract) class that inherits from it. You can only use the abstract class as a variable/argument type. To guarantee that only stuff that inherits from it can be used there.
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use.
Then use the abstract class as type argument. It means only instaces of the abstract class (of wich there can be no instance) or instances of classes that inherit from it (that somebody else writes) can be used at that place.
Note that Abstract classes and Interfaces overlap in nearly all uses. There is a miriad small differences, but I do not think they mater. The only big difference I can see, is one of exclusivity:
a class can implement as many Interfaces as it wants.
You can only inherit from one abstract class. that means it is for a primary, exclusive purpose. That way you prevent some dumb ideas, like someone trying to make a Windows Form that is also a DBConnection.

Action delegate parameters do not match using implemented abstract class

I have the following abstract class:
public abstract class BaseClass{
public object contents { get; set; }
public Action<BaseClass> mutator;
public abstract void Initialise();
}
This will be used by several classes, which will override the Initialize method to assign a value to contents, which will in turn be mutated using the mutator delegate at specific points in time.
I have the following static class, with each method intended to be used as a mutator:
public static class Mutators{
public static void VariantA(A inputObj){
// inputObj.contents = something else
}
public static void VariantB(A inputObj) { } // etc. etc.
}
I then have class A, which implements BaseClass. I am trying to assign Mutators.VariantA to the mutator delegate, but i'm not able to.
public class A : BaseClass{
public A(){
mutator = Mutators.VariantA;
}
public override void Initialise(){
/* set the value of contents property here */
}
}
Specifically I get the following error: A method or delegateMutators.VariantA(A)' parameters do not match delegate System.Action<BaseClass>(BaseClass)' parameters (CS0123)
I understand that Mutators.VariantA(A) requires an object of type A, and the Action was declared to accept an input of type BaseClass, however as class A implements BaseClass I thought I would have been able to do this ?
Coming from dynamically typed languages i'm having a tough time getting to grips with working with types in this way :(
Is there any way I can point to a function with an input of the abstract type in this way ? Do I need to look at some other design pattern ?
Thanks
I understand that Mutators.VariantA(A) requires an object of type A, and the Action was declared to accept an input of type BaseClass, however as class A implements BaseClass I thought I would have been able to do this ?
Absolutely not.
An Action<BaseClass> has to be able to accept any BaseClass object. So for example, if your code were valid, I would be able to write:
Action<BaseClass> mutator = Mutators.VariantA;
mutator.Invoke(new B());
(Where B is another class derived from BaseClass.)
The fact that B derives from BaseClass makes it valid for the invocation - but it's not going to help your VariantA method work nicely.
It's not really clear why you have a mutator here - I strongly suspect you should abstract BaseClass from its mutations. I still don't follow what you're trying to achieve, but this design pattern isn't going to help you get there in a type-safe way.
You could write:
public abstract class BaseClass<T> where T : BaseClass<T> {
public object Contents { get; set; }
public Action<T> Mutator { get; set; }
public abstract void Initialise();
}
... then:
public class A : BaseClass<A> {
public A() {
Mutator = Mutators.VariantA;
}
}
... as then you'd be writing something which can mutate "A" values. But in my experience this sort of generic nesting gets really messy, really quickly.
I've used your current example and changed the Method Signature of one of the classes to the following and it works
public abstract class BaseClass
{
public object contents { get; set; }
public Action<BaseClass> mutator;
public abstract void Initialise();
}
public static class Mutators
{
public static void VariantA(BaseClass baseClass)
{
// inputObj.contents = something else
}
public static void VariantB(A inputObj) { } // etc. etc.
}
public class A : BaseClass
{
public A()
{
mutator = Mutators.VariantA;
}
public override void Initialise()
{
/* set the value of contents property here */
}
}

Class both extends an abstract class and implements an interface

What if I have a class that both extends an abstract class and implements an interface, for example:
class Example : AbstractExample, ExampleInterface
{
// class content here
}
How can I initialize this class so I can access methods from both the interface and the abstract class?
When I do:
AbstractExample example = new Example();
I cannot access methods from the interface.
You need to
implement the interface in AbstractExample
or get a reference to Example
Example example = new Example();
The last example will tie you to a solid instance of either the interface or abstract class which I presume is not your goal.The bad news is you're NOT in a dynamically typed language here, so your stuck with either having a reference to a solid "Example" objects as previously sprcified or casting/uncasting i.e:
AbstractExample example = new Example();
((IExampleInterface)example).DoSomeMethodDefinedInInterface();
Your other alternitives are to have both AbstractExample and IExampleInterface implement a common interface so you would have i.e.
abstract class AbstractExample : ICommonInterface
interface IExampleInterface : ICommonInterface
class Example : AbstractExample, IExampleInterface
Now you could work with ICommonInterface and have the functionality of both the abstract class and the implementation of your IExample interface.
If none of these answers are acceptable, you may want to look at some of the DLR languages that run under the .NET framework i.e. IronPython.
If you only know the abstract class, it suggests that you know the actual type via an instance of Type. Therefore, you could use generics:
private T SomeMethod<T>()
where T : new(), AbstractExample, ExampleInterface
{
T instance = new T();
instance.SomeMethodOnAbstractClass();
instance.SomeMethodOnInterface();
return instance;
}
Use:
Example example = new Example();
Updated after more information:
If you are sure it implements ExampleInterface, you can use
AbstractClass example = new Example();
ExampleInterface exampleInterface = (ExampleInterface)example;
exampleInterface.InterfaceMethod();
You can also make sure it really implements it by checking the interface with
if (example is ExampleInterface) {
// Cast to ExampleInterface like above and call its methods.
}
I don't believe Generics help you as those are resolved compile time and if you only have a reference to the AbstractClass the compiler will complain.
Edit: So more or less what Owen said. :)
I think this example will help you:
public interface ICrud
{
void Add();
void Update();
void Delete();
void Select();
}
public abstract class CrudBase
{
public void Add()
{
Console.WriteLine("Performing add operation...");
Console.ReadLine();
}
public void Update()
{
Console.WriteLine("Performing update operation...");
Console.ReadLine();
}
public void Delete()
{
Console.WriteLine("Performing delete operation...");
Console.ReadLine();
}
public void Select()
{
Console.WriteLine("Performing select operation...");
Console.ReadLine();
}
}
public class ProcessData : CrudBase, ICrud
{
}
var process = new ProcessData();
process.Add();

Why can't I declare C# methods virtual and static?

I have a helper class that is just a bunch of static methods and would like to subclass the helper class. Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in order to access virtual method).
Is there any way around this? I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod(). Brownie points for anyone that can point out some languages that support virtual static methods.
Edit: OK yeah I'm crazy. Google search results had me thinking I wasn't for a bit there.
I don't think you are crazy. You just want to use what is impossible currently in .NET.
Your request for virtual static method would have so much sense if we are talking about generics.
For example my future request for CLR designers is to allow me to write intereface like this:
public interface ISumable<T>
{
static T Add(T left, T right);
}
and use it like this:
public T Aggregate<T>(T left, T right) where T : ISumable<T>
{
return T.Add(left, right);
}
But it's impossible right now, so I'm doing it like this:
public static class Static<T> where T : new()
{
public static T Value = new T();
}
public interface ISumable<T>
{
T Add(T left, T right);
}
public T Aggregate<T>(T left, T right) where T : ISumable<T>, new()
{
return Static<T>.Value.Add(left, right);
}
Virtual static methods don't make sense. If I call HelperClass.HelperMethod();, why would I expect some random subclass' method to be called? The solution really breaks down when you have 2 subclasses of HelperClass - which one would you use?
If you want to have overrideable static-type methods you should probably go with:
A singleton, if you want the same subclass to be used globally.
A tradition class hierarchy, with a factory or dependency injection, if you want different behavior in different parts of your application.
Choose whichever solution makes more sense in your situation.
You can achieve the same effect by just having a regular static method and then shadow it with the new keyword
public class Base
{
//Other stuff
public static void DoSomething()
{
Console.WriteLine("Base");
}
}
public class SomeClass : Base
{
public new static void DoSomething()
{
Console.WriteLine("SomeClass");
}
}
public class SomeOtherClass : Base
{
}
Then you can call the methods like so
Base.DoSomething(); //Base
SomeClass.DoSomething(); //SomeClass
SomeOtherClass.DoSomething(); //Base
Indeed, this can be done in Delphi. An example:
type
TForm1 = class(TForm)
procedure FormShow(Sender: TObject);
end;
TTestClass = class
public
class procedure TestMethod(); virtual;
end;
TTestDerivedClass = class(TTestClass)
public
class procedure TestMethod(); override;
end;
TTestMetaClass = class of TTestClass;
var
Form1: TForm1;
implementation
{$R *.dfm}
class procedure TTestClass.TestMethod();
begin
Application.MessageBox('base', 'Message');
end;
class procedure TTestDerivedClass.TestMethod();
begin
Application.MessageBox('descendant', 'Message');
end;
procedure TForm1.FormShow(Sender: TObject);
var
sample: TTestMetaClass;
begin
sample := TTestClass;
sample.TestMethod;
sample := TTestDerivedClass;
sample.TestMethod;
end;
Quite interesting. I no longer use Delphi, but I recall being able to very easily create different types of controls on a custom designer canvas using the metaclass feature: the control class, eg. TButton, TTextBox etc. was a parameter, and I could call the appropriate constructor using the actual metaclass argument.
Kind of the poor man's factory pattern :)
I come from Delphi and this is a feature among many that I sorely miss in c#. Delphi would allow you to create typed type references and you could pass the type of a derived class wherever the type of a parent class was needed. This treatment of types as objects had powerful utility. In particular allowing run time determination of meta data. I am horribly mixing syntax here but in c# it would look something like:
class Root {
public static virtual string TestMethod() {return "Root"; }
}
TRootClass = class of TRoot; // Here is the typed type declaration
class Derived : Root {
public static overide string TestMethod(){ return "derived"; }
}
class Test {
public static string Run(){
TRootClass rc;
rc = Root;
Test(rc);
rc = Derived();
Test(rc);
}
public static Test(TRootClass AClass){
string str = AClass.TestMethod();
Console.WriteLine(str);
}
}
would produce:
Root
derived
You are not crazy. What you are referring to is called Late Static Binding; it's been recently added to PHP. There's a great thread that describes it - here: When would you need to use late static binding?
a static method exists outside of an instance of a class. It cannot use any non-static data.
a virtual method will be "overwritten" by an overloaded function depending of the type of an instance.
so you have a clear contradiction between static and virtual.
This is not a problem of support, It is a concept.
Update: I was proven wrong here(see comments):
So I doubt you will find any OOP-Language which will support virtual
static methods.
There is a way to force an inheritance of "abstract static" methods from an abstract generic class. See as follow :
public abstract class Mother<T> where T : Mother<T>, new()
{
public abstract void DoSomething();
public static void Do()
{
(new T()).DoSomething();
}
}
public class ChildA : Mother<ChildA>
{
public override void DoSomething() { /* Your Code */ }
}
public class ChildB : Mother<ChildB>
{
public override void DoSomething() { /* Your Code */ }
}
Example (using the previous Mother):
public class ChildA : Mother<ChildA>
{
public override void DoSomething() { Console.WriteLine("42"); }
}
public class ChildB : Mother<ChildB>
{
public override void DoSomething() { Console.WriteLine("12"); }
}
public class Program
{
static void Main()
{
ChildA.Do(); //42
ChildB.Do(); //12
Console.ReadKey();
}
}
It's not that great since you can inherit from only one abstract class and it will ask you to be lenient with your new() implementation.
More, I think it will be costly memory-wise depending on the size of your inherited classes.
In case you have memory issue, you would have to set every properties/variables after your new in a public method which is an awful way to have default values.
I heard that Delphi suports something like this. It seems it does it by making classes object instances of a metaclass.
I've not seen it work, so I'm not sure that it works, or what's the point for that.
P.S. Please correct me if I'm wrong, since it's not my domain.
Because a virtual method uses the defined type of the instantiated object to determine which implementation to execute, (as opposed to the declared type of the reference variable)
... and static, of course, is all about not caring if there's even an instantiated instance of the class at all...
So these are incompatible.
Bottom line, is if you want to change behavior based on which subclass an instance is, then the methods should have been virtual methods on the base class, not static methods.
But, as you already have these static methods, and now need to override them, you can solve your problem by this:
Add virtual instance methods to the base class that simply delegate to the static methods, and then override those virtual instance wrapper methods (not the static ones) in each derived subclass, as appropriate...
It is actually possible to combine virtual and static for a method or a member by using the keyword new instead of virtual.
Here is an example:
class Car
{
public static int TyreCount = 4;
public virtual int GetTyreCount() { return TyreCount; }
}
class Tricar : Car
{
public static new int TyreCount = 3;
public override int GetTyreCount() { return TyreCount; }
}
...
Car[] cc = new Car[] { new Tricar(), new Car() };
int t0 = cc[0].GetTyreCount(); // t0 == 3
int t1 = cc[1].GetTyreCount(); // t1 == 4
Obviously the TyreCount value could have been set in the overridden GetTyreCount method, but this avoids duplicating the value. It is possible to get the value both from the class and the class instance.
Now can someone find a really intelligent usage of that feature?
Mart got it right with the 'new' keyword.
I actually got here because I needed this type of functionality and Mart's solution works fine. In fact I took it one better and made my base class method abstract to force the programmer to supply this field.
My scenario was as follows:
I have a base class HouseDeed. Each House type is derived from HouseDeed must have a price.
Here is the partial base HouseDeed class:
public abstract class HouseDeed : Item
{
public static int m_price = 0;
public abstract int Price { get; }
/* more impl here */
}
Now lets look at two derived house types:
public class FieldStoneHouseDeed : HouseDeed
{
public static new int m_price = 43800;
public override int Price { get { return m_price; } }
/* more impl here */
}
and...
public class SmallTowerDeed : HouseDeed
{
public static new int m_price = 88500;
public override int Price { get { return m_price; } }
/* more impl here */
}
As you can see I can access the price of the house via type SmallTowerDeed.m_price, and the instance new SmallTowerDeed().Price
And being abstract, this mechanism nags the programmer into supplying a price for each new derived house type.
Someone pointed how 'static virtual' and 'virtual' are conceptually at odds with one another. I disagree. In this example, the static methods do not need access to the instance data, and so the requirements that (1) the price be available via the TYPE alone, and that (2) a price be supplied are met.
An override method provides a new implementation of a member that is inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
You cannot use the new, static, or virtual modifiers to modify an override method.
An overriding property declaration must specify exactly the same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override.
You can use the new keyword
namespace AspDotNetStorefront
{
// This Class is need to override StudioOnlineCommonHelper Methods in a branch
public class StudioOnlineCommonHelper : StudioOnlineCore.StudioOnlineCommonHelper
{
//
public static new void DoBusinessRulesChecks(Page page)
{
StudioOnlineCore.StudioOnlineCommonHelper.DoBusinessRulesChecks(page);
}
}
}
It is possible to simulate the functionality by using the new keyword in the derived class and throwing the NotSupportedException() in the base.
public class BaseClass{
public static string GetString(){
throw new NotSupportedException(); // This is not possible
}
}
public class DerivedClassA : BaseClass {
public static new string GetString(){
return "This is derived class A";
}
}
public class DerivedClassB : BaseClass {
public static new string GetString(){
return "This is derived class B";
}
}
static public void Main(String[] args)
{
Console.WriteLine(DerivedClassA.GetString()); // Prints "This is derived class A"
Console.WriteLine(DerivedClassB.GetString()); // Prints "This is derived class B"
Console.WriteLine(BaseClass.GetString()); // Throws NotSupportedException
}
Due to the fact that it is not possible to detect this condition at compile time and that IntelliSense won't suggest that such function should be implemented in the derived class, this is a potential headache.
One comment also suggested to use NotImplemetedException(). Microsoft's documentation indicates that neither of these exceptions should be handled so any of them should work.
The differences between NotSupportedException and NotImplemetedException are commented in this blog.
You will be able to soon, in C# 11!
From Tutorial: Explore C# 11 feature - static virtual members in interfaces:
C# 11 and .NET 7 include static virtual members in interfaces. This feature enables you to define interfaces that include overloaded operators or other static members.

Categories

Resources