Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object expression for abstract class without abstract members

Tags:

f#

Given an interface without members

type IFoo = interface end

it's possible to create an instance using an object expression

let foo = { new IFoo }

However, it doesn't seem possible to do the same with an abstract class having no abstract members.

[<AbstractClass>]
type Foo() = class end

let foo = { new Foo() }

gives the error: Invalid object expression. Objects without overrides or interfaces should use the expression form 'new Type(args)' without braces. Well, we know that won't work either.

Here's a hacky workaround

let foo = { new Foo() with member __.ToString() = base.ToString() }

Is there a better way to create an object expression for an abstract type without abstract members?

like image 543
Daniel Avatar asked Nov 16 '11 16:11

Daniel


People also ask

Can we create object of abstract class without abstract method?

Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user. An abstract class having both abstract methods and non-abstract methods. For an abstract class, we are not able to create an object directly.

What is the use of abstract class without abstract method?

Abstract class without abstract method means you can create object of that abstract class. See my Example. If you write one abstract method inside abstract class then it will not compile. Which means if you create abstract class without abstract method then you can create Object of that Abstract Class.

Can abstract class have non-abstract variables?

An abstract class can have abstract and non-abstract methods.

Can we have object for abstract class?

Abstract Classes and Methods Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).


1 Answers

I don't think there's a better way.

I also don't know why you'd want to do this (abstract class with no members), but I'll just assume you have your reasons and leave it at that :)

like image 188
Brian Avatar answered Sep 28 '22 11:09

Brian