Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class constructor access modifier

Tags:

java

An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of protected and public is the correct access modifier to use, since the abstract type seems to indicate that technically a public constructor will act very much protected? Should I just use protected on all my constructors?

like image 606
Richard Walton Avatar asked Nov 04 '08 03:11

Richard Walton


People also ask

Can abstract class have access modifiers?

An Abstract class can have access modifiers like private, protected, and internal with class members. But abstract members cannot have a private access modifier. An Abstract class can have instance variables (like constants and fields). An abstract class can have constructors and destructors.

Which access modifier is allowed for a constructor?

Like methods, constructors can have any of the access modifiers: public, protected, private, or none (often called package or friendly). Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract , final , native , static , or synchronized .

Can we use constructor in abstract class?

An abstract class can be inherited by any number of sub-classes, thus functionality of constructor present in abstract class can be used by them. The constructor inside the abstract class can only be called during constructor chaining i.e. when we create an instance of sub-classes.


1 Answers

since the abstract type seems to indicate that technically a public constructor will act very much protected

This is not correct. An abstract class cannot be directly instatiated by calling its constructor, however, any concrete implementation will inherit the abstract class' methods and visibility

So the abstract class can certainly have public constructors.

Actually, the abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.:

public class Scratch {     public static abstract class A     {         public A( int i ) {}     }      public static class B extends A     {         private B() { super(0); };     } } 
like image 191
Jordan Stewart Avatar answered Sep 23 '22 21:09

Jordan Stewart