Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an abstract class? [duplicate]

Tags:

java

c#

oop

When I learned about abstract classes is said WT(H*)!!!

QUESTIONS:

  1. What is the point of creating a class that can't be instantiated?
  2. Why would anybody want such a class?
  3. What is the situation in which abstract classes become NECESSARY?

**if you know what i mean*

like image 930
Pratik Deoghare Avatar asked Dec 16 '09 05:12

Pratik Deoghare


People also ask

Can a class have 2 abstract methods?

abstract classes can't be instantiated, only subclassed. other classes extend abstract classes. can have both abstract and concrete methods. similar to interfaces, but (1) can implement methods, (2) fields can have various access modifiers, and (3) subclasses can only extend one abstract class.

Is an abstract class a blueprint?

An Abstract Class is basically a blueprint that should only ever be extended by child classes and not used directly. By extending the blueprint, the developer can ensure that the basic functionality is present in the child class in order for it to be functional.

What is an abstract class?

An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.

Do abstract classes have to be overriden?

To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.


1 Answers

  1. most commonly to serve as a base-class or interface (some languages have a separate interface construct, some don't) - it doesn't know the implementation (that is to be provided by the subclasses / implementing classes)
  2. abstraction and re-use
  3. when the base-class can provide no meaningful default-implementation for a method (but allowing subclasses to re-use the non-abstract parts of the implementation; any fields, non-abstract methods, etc)

For example:

public abstract class Stream { /* lots of code, some abstract methods */ }

What the heck is a stream by itself? What kind of stream? a stream to a file? a network? a memory buffer? Each may have different and unrelated ways of reading / writing, but provide a common API. It makes no sense to create just a Stream, but via the abstract class, you can code to the Stream API without knowing the details:

Stream s = CreateStream(...); // I don't *care* what kind of stream
s.Write(new byte[] {1,2,3,4,5});
s.Close();
like image 166
Marc Gravell Avatar answered Oct 03 '22 12:10

Marc Gravell