简体   繁体   中英

How is a static method returning a object of its own abstract class - WebRequest

While working on the WebRequest class I noticed that it is an abstract class, and it has a create method which is returning a object of the abstract class.

I have read that abstract class cannot be instantiated, so i'm trying to understand how the static method is returning the object

WebRequest req = WebRequest.Create(URl);

Create Method definition:

public static WebRequest Create(string requestUriString);

See Documentation

i tried this, and as expected got an error

abstract class Test
    {
        public static Test Runmachine()
        {
            return new Test();

        }
    }

Try this and see for yourself. You can return a more specialized, non-abstract version of the same class, eg a class that derives from Test .

abstract class Test
{
    public static Test RunMachine()
    {
        return new SpecializedTest();
    }
}

class SpecializedTest : Test {}

I guess what you have missed, is Polymorphism.If you have a base class A and a derived class B, any object of type B, is also of type A. In other words any object of type B can be assigned to a variable of type A. In your case, the return type of the method being WebRequest, doesn't mean that the returned object is a direct instance of WebRequest. It can -and since WebRequest is abstract, it has to- be an instance of a derived class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM