Java public static constructor

Почему статический конструктор Java не разрешен?

Статический конструктор Java не разрешен, но почему? Прежде чем мы углубимся в причины запрета статического конструктора, давайте посмотрим, что произойдет, если мы захотим сделать конструктор статичным.

Статический конструктор Java

Допустим, у нас есть класс, определенный как:

Если вы попытаетесь скомпилировать этот класс, вы получите сообщение об ошибке как Незаконный модификатор для конструктора в типе данных; разрешены только общедоступные, защищенные и частные .

Почему статический конструктор не разрешен?

Давайте рассмотрим некоторые из причин, которые приводят убедительные аргументы в пользу запрета статического конструктора в java.

Статика принадлежит классу, Конструктор-объекту

Мы знаем, что статические методы, блоки или переменные принадлежат классу. В то время как конструктор принадлежит объекту и вызывается, когда мы используем оператор new для создания экземпляра. Поскольку конструктор не является свойством класса, имеет смысл, что он не может быть статичным.

Статический блок/метод не может получить доступ к нестатическим переменным

Мы знаем, что статические методы не могут получить доступ к нестатическим переменным. То же самое верно и для статического блока.

Теперь основная цель конструктора-инициализировать переменные объекта. Поэтому, если мы сделаем конструктор статическим, он не сможет инициализировать переменные объекта. Это разрушит всю цель наличия конструктора для создания объекта. Таким образом, оправдано, чтобы конструктор был нестатичным.

Обратите внимание, что мы не можем использовать это внутри статического метода для ссылки на переменную объекта. Приведенный ниже код выдаст ошибку компиляции как: Не может использовать это в статическом контексте .

public static void main(String args[])

Статический конструктор нарушит наследование

В Java каждый класс неявно расширяет класс объектов. Мы можем определить иерархию классов, в которой конструктор подкласса вызывает конструктор суперкласса. Это делается с помощью вызова метода super () . В большинстве случаев JVM автоматически вызывает конструктор суперкласса, но иногда нам приходится вызывать их вручную, если в суперклассе несколько конструкторов.

Давайте рассмотрим пример использования super () .

package com.journaldev.util; class Data < Data() < System.out.println("Data Constructor"); >> public class DataChild extends Data < public DataChild() < super(); //JRE calls it explicitly, calling here for explanation System.out.println("DataChild Constructor"); >public static void main(String args[]) < DataChild dc = new DataChild(); >>

Вышеприведенная программа выдаст следующий результат.

Data Constructor DataChild Constructor

Если вы посмотрите на метод super () , он не статичен. Поэтому, если конструктор станет статичным, мы не сможем его использовать, и это нарушит наследование в java .

Альтернатива статическому конструктору Java

Если вы хотите инициализировать некоторые статические переменные в классе, вы можете использовать статический блок. Обратите внимание, что мы не можем передавать аргументы в статический блок, поэтому, если вы хотите инициализировать статические переменные, вы можете сделать это и в обычном конструкторе.

Читайте также:  Form border color css

Резюме

Статический конструктор Java не разрешен, и у нас есть для этого очень веские причины. Мы можем инициализировать статические переменные с помощью статического блока, а также с помощью самого конструктора.

Читайте ещё по теме:

Источник

Java public static constructor

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Java static constructor – Is it really Possible to have them in Java?

Have you heard of static constructor in Java? I guess yes but the fact is that they are not allowed in Java. A constructor can not be marked as static in Java. Before I explain the reason let’s have a look at the following piece of code:

public class StaticTest < /* See below - I have marked the constructor as static */ public static StaticTest() < System.out.println("Static Constructor of the class"); >public static void main(String args[]) < /*Below: I'm trying to create an object of the class *that should invoke the constructor */ StaticTest obj = new StaticTest(); >>

Output: You would get the following error message when you try to run the above java code.
“modifier static not allowed here”

Why java doesn’t support static constructor?

It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.
Lets back to the point, since each constructor is being called by its subclass during creation of the object of its subclass, so if you mark constructor as static the subclass will not be able to access the constructor of its parent class because it is marked static and thus belong to the class only. This will violate the whole purpose of inheritance concept and that is reason why a constructor cannot be static.

Let’s understand this with the help of an example –

StaticConstructorExample

public class StaticDemo < public StaticDemo() < /*Constructor of this class*/ System.out.println("StaticDemo"); >> public class StaticDemoChild extends StaticDemo < public StaticDemoChild() < /*By default super() is hidden here */ System.out.println("StaticDemoChild"); >public void display() < System.out.println("Just a method of child class"); >public static void main(String args[]) < StaticDemoChild obj = new StaticDemoChild(); obj.display(); >>

Output:
StaticDemo
StaticDemoChild
Just a method of child class

Читайте также:  Java io streamcorruptedexception invalid stream header 00000000

Did you notice? When we created the object of child class, it first invoked the constructor of parent class and then the constructor of it’s own class. It happened because the new keyword creates the object and then invokes the constructor for initialization, since every child class constructor by default has super() as first statement which calls it’s parent class’s constructor. The statement super() is used to call the parent class(base class) constructor.

This is the reason why constructor cannot be static – Because if we make them static they cannot be called from child class thus object of child class cannot be created.

Another good point mentioned by Prashanth in the comment section: Constructor definition should not be static because constructor will be called each and every time when object is created. If you made constructor as static then the constructor will be called before object creation same like main method.

Static Constructor Alternative – Static Blocks

Java has static blocks which can be treated as static constructor. Let’s consider the below program –

Static-Block-Example

public class StaticDemo < static< System.out.println("static block of parent class"); >> public class StaticDemoChild extends StaticDemo < static< System.out.println("static block of child class"); >public void display() < System.out.println("Just a method of child class"); >public static void main(String args[]) < StaticDemoChild obj = new StaticDemoChild(); obj.display(); >>

Output:
static block of parent class
static block of child class
Just a method of child class

In the above example we have used static blocks in both the classes which worked perfectly. We cannot use static constructor so it’s a good alternative if we want to perform a static task during object creation.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Hi Pravat, You can overload a static method but you can’t override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.

static member can be inherited but cannot be overridded by subclass. class Parent < static int i = 10; public static void method()
< System.out.println(i); >
> class Child extends Parent < public void abc ()
< method(); // child class is inheriting static method >public static void main (String args[])
Modifier m = new Modifier(); m.abc(); >
>

Hi, You have mentioned as “It’s actually pretty simple to understand – static method cannot be inherited in the sub class. ” Shouldn’t it be “static constructor cannot be inherited in the subclass”. Please correct me if I am wrong.

Читайте также:  Public string get java

That is just an example to demonstrate the purpose of static keyword. I have edited the post to make it more clear. I hope its clear now. let me know I you have any other questions.

I was searching this concept on [Stackoverflow] and in-between i lied up here.Very good explanation.Can you tell me the use of Method hiding ?

You would never find it in the production code or anywhere else because static constructors are not allowed in java and this post is to discuss the reason of it. This is the most common question that is asked during interview so here we are discuss why something is not allowed in java.

this explanation is not right.
First constructors are not inherited at all does not matter static or non-static.
Second if we even go by your concept & treat constructors as methods so the constructors have default(package-private) access specifier.It means it won’t be available in the child class. Constructors are not static coz they violate the basic meaning of static. Static means something which is the property of a class while constructors are something which are property of an object so the reason is “concept of static constructor is basic design violation”.

Deepak, The points you mentioned are correct. However I did not mention anywhere in the article that constructors are inherited. I just pointed out that they are being invoked during object creation of sub class, that’s all. Also, constructors are not methods because they do not have a return type. I think you got confused because of an ambiguous statement mentioned in the post. I just added more details to the post to make it easy to understand. I hope its clear now.

Hi Arkya,
If you want to make something happen before your object has created. Say you want to read a file and then decide which object you want to create. it happens in real time. In that case it is useful…

You probably want to underline that static block is only called only before the first instance of the class is created.

TO add one more point that constructor is static create static method in class and create object of that class in that staic method ie
class myclass myclass() sysout(“constructor of class”)
>
static myclass getObject return new myclass();
>
>
Think how we are able to access constructor from static method give

probably you have a mistake in comment to code
/*By default this() is hidden here */
here should be “super” not “this”.

Constructor definition should not be static because constructor will be called each and every time when object is created. If you made constructor as static then the constructor will be called before object creation same like main method.

Источник

Оцените статью