Return в конструкторе java

Does a constructor have a return type in Java?

No, constructor does not have any return type in Java.

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.

If the programmer doesn’t write a constructor the compiler writes a constructors on his behalf.

Example

If you closely observe the declaration of the constructor in the following example it just have the name of the constructor which is similar to class and, the parameters. It does not have any return type.

public class DemoTest < String name; int age; DemoTest(String name, int age)< this.name = name; this.age = age; System.out.println("This is the constructor of the demo class"); >public static void main(String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Enter the value of name: "); String name = sc.nextLine(); System.out.println("Enter the value of age: "); int age = sc.nextInt(); DemoTest obj = new DemoTest(name, age); System.out.println("Value of the instance variable name: "+name); System.out.println("Value of the instance variable age: "+age); >>

Output

Enter the value of name: Krishna Enter the value of age: 29 This is the constructor of the demo class Value of the instance variable name: Krishna Value of the instance variable age: 29

Monica Mona

Student of life, and a lifelong learner

Источник

как объяснить оператор возврата в конструкторе?

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

Hussain Akhtar Wahid ‘Ghouri’

Вы слышали о соглашениях об именах Java? — Nikolay Kuznetsov

Программа вообще не компилируется: выдает ошибку компиляции для оператора unreachable. — user207421

@EJP: эй, это было непреднамеренно, последняя строка, которую я написал по ошибке, ее там не должно было быть — Hussain Akhtar Wahid ‘Ghouri’

«который будет возвращать VOID, но конструктор не должен ничего возвращать. «. На самом деле конструктор компилируется в специальный метод, называемый который возвращает пустоту. — AMDG

6 ответы

return в конструкторе просто выпрыгивает из конструктора в указанную точку. Вы можете использовать его, если вам не нужно полностью инициализировать класс в некоторых обстоятельствах.

// A real life example class MyDate < // Create a date structure from a day of the year (1..366) MyDate(int dayOfTheYear, int year) < if (dayOfTheYear < 1 || dayOfTheYear >366) < mDateValid = false; return; >if (dayOfTheYear == 366 && !isLeapYear(year)) < mDateValid = false; return; >// Continue converting dayOfTheYear to a dd/mm. // . 

return можно использовать для немедленного выхода из конструктора. Одним из вариантов использования, по-видимому, является создание наполовину инициализированных объектов.

Читайте также:  Как изменить размер cmd python

Можно спорить, хорошая ли это идея. Проблема ИМХО в том, что с результирующими объектами сложно работать, так как у них нет никаких инвариантов, на которые можно было бы положиться.

Во всех примерах, которые я видел до сих пор, которые использовали return в конструкторе код был проблематичным. Часто конструкторы были слишком большими и содержали слишком много бизнес-логики, что затрудняло их тестирование.

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

Лучше убрать всю логику из конструкторов и стремиться к полностью инициализированным небольшим объектам. Тогда вам редко (если вообще когда-либо) нужно будет звонить return в конструкторе.

заявления после возвращение заявление будет недостижимо. Если оператор return является последним, то его определение в конструкторе бесполезно, но компилятор все равно не жалуется. Он компилируется нормально.

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

public class CheckDataAvailability < Connection con =SomeDeligatorClass.getConnection(); public CheckDataAvailability() //this is constructor < if(conn!=null) < //do some database connection stuff and retrieve values; return; // after this following code will not be executed. >FileReader fr; // code further from here will not be executed if above 'if' condition is true, because there is return statement at the end of above 'if' block. > > 

Методы, объявленные с void тип возвращаемого значения, а также конструкторы просто ничего не возвращают. Вот почему вы можете опустить return Заявление в них вообще. Причина почему void возвращаемый тип не указан для конструкторов, чтобы отличить конструктор от одноименного метода:

public class A < public A () // This is constructor < >public void A () // This is method < >> 

ответ дан 04 мар ’13, в 06:03

В этом случае return действует аналогично break . На этом инициализация заканчивается. Представьте себе класс, в котором int var . Ты сдал int[] values и хочу инициализировать var к любому положительному int Хранится в values (или var = 0 в противном случае). Затем вы можете использовать return .

public class MyClass < int var; public MyClass(int[] values)< for(int i : values)< if(i >0) < var = i; return; >> > //other methods > 
public class Demo < Demo()< System.out.println("hello"); return; >> class Student < public static void main(String args[])< Demo d=new Demo(); >> //output will be -----------"hello" public class Demo < Demo()< return; System.out.println("hello"); >> class Student < public static void main(String args[])< Demo d=new Demo(); >> //it will throw Error 

Добро пожаловать в StackOverflow! Пожалуйста, не просто сбрасывайте сюда свой код, постарайтесь дать хорошее описание вашего ответа. Пожалуйста, найдите время, чтобы прочитать это: stackoverflow.com/help/how-to-answer — sɐunıɔ ןɐ qɐp

Читайте также:  System library image php

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками java constructor return or задайте свой вопрос.

Источник

Return в конструкторе java

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

Источник

Constructor in Java – OOP Concept

This tutorial will guide you on what is a constructor in Java. You will know how to write a constructor method for a class and instantiate its object.

Basics of Constructor in Java

You can go through the following sections to learn about Java constructor.

Constructor in Java

What is a constructor in Java?

A constructor is a specialized routine which acts as a callback function. It means that you don’t need to call it explicitly. Java invokes it automatically while creating the object of a class.

Please note that constructors don’t have a defined return type. Usually, you will utilize a constructor to give initial values to the local class variables characterized within the class or to play out some other start-up process required to make a new object.

What is default constructor?

All classes have constructors, regardless of whether you create one or not. Java provides a default constructor for every class. The default constructor sets all member variables to zero.

Constructor Syntax

class className < // Constructor className() < // . >// Other methods… void method1() < // . >void method2() < // . >>

When is a constructor called in Java?

Whenever your program creates an object using the new() operator, Java runtime checks whether you have an explicit constructor or not.

If it finds one, then it invokes the user-defined constructor else executes the default one that Java provides.

// Create a TestConstructor class public class TestConstructor < int attribute; // Create a class member // Create an eattributeplicit constructor for the TestConstructor class public TestConstructor() < attribute = 1; // Set the initial value for the class attribute attribute >public static void main(String[] args) < TestConstructor object = new TestConstructor(); // Create an object of class TestConstructor (It'll trigger the constructor) System.out.println(object.attribute); // Display the result >>

Types of Constructors

Constructors for Java are mainly of two types:

No Argument Constructors:

This constructor is useful when the programmer does not want to provide any parameters for the object variables or members. With the help of no argument constructors,

Читайте также:  Java switch string to int
No Argument Constructor Example:

Check out the sample code for the no argument constructor:

public class NoArgConstructor < int data; public NoArgConstructor( /* No Arguments are passed here */) < data = 100; >public static void main(String[] args) < NoArgConstructor oj = new NoArgConstructor(); System.out.println("data : " + oj.data); >>

When the programmer needs to define new objects with user-defined values or values that change with time, the programmer needs a constructor that accepts these values as one or more parameters from the user or define them himself.

  • We can pass parameters or values to a constructor in a similar way as for any other method.
  • Parameters are specified within the parentheses after mentioning the constructor’s name.
Parameterized Constructor Example:

Constructors can accept parameters that help to set the attribute values.

public class Laptop < int model_year; String model_make; String model_name; public Laptop(int year, String make, String name) < model_year = year; model_make = make; model_name = name; >public static void main(String[] args) < Laptop myLaptop = new Laptop(2019, "Dell", "Latitude"); System.out.println(myLaptop.model_year + " " + myLaptop.model_make + " " + myLaptop.model_name); >>

What does a constructor return in Java?

Like other OOP languages, constructors in Java don’t have a return statement to return any user-defined value.

However, they do return the current class instance. Also, it is perfectly alright to add a “return;” statement towards the end of a constructor method.

If you write it before any executable statement, then unreachable statement error would occur.

public class TestConstructorReturn < int data; public TestConstructorReturn( ) < data = -1; return; >public static void main(String[] args) < TestConstructorReturn oj = new TestConstructorReturn(); System.out.println("data : " + oj.data); >>

Constructor Overloading in Java

Java allows overloading of constructors. Its JVM can identify constructors depending on numbers of parameters, their types, and the sequence.

See the example below to understand this concept more clearly.

public class ConstructorOverloading < int a; double b; public ConstructorOverloading( ) < System.out.println("No argument contructor called."); a = 0; b = 0.0; >public ConstructorOverloading( int a, double b) < System.out.format("Order (%d, %f) based contructor called.\n", a, b); this.a = a; this.b = 0.0; >public ConstructorOverloading( double b, int a) < System.out.format("Order (%f, %d) based contructor called.\n", b, a); this.a = 0; this.b = b; >public ConstructorOverloading( int value) < System.out.format("Type (int: %d) based contructor called.\n", value); this.a = value; this.b = 0.0; >public ConstructorOverloading( double value) < System.out.format("Type (double: %f) based contructor called.\n", value); this.b = value; this.a = 0; >public static void main(String[] args) < ConstructorOverloading o1 = new ConstructorOverloading(); System.out.format("a : %d, b : %f \n\n", o1.a, o1.b); ConstructorOverloading o2 = new ConstructorOverloading(1, 1.1); System.out.format("a : %d, b : %f \n\n", o2.a, o2.b); ConstructorOverloading o3 = new ConstructorOverloading(1.1, 1); System.out.format("a : %d, b : %f \n\n", o3.a, o3.b); ConstructorOverloading o4 = new ConstructorOverloading(1); System.out.format("a : %d, b : %f \n\n", o4.a, o4.b); ConstructorOverloading o5 = new ConstructorOverloading(1.1); System.out.format("a : %d, b : %f \n\n", o5.a, o5.b); >>
No argument contructor called. a : 0, b : 0.000000 Order (1, 1.100000) based contructor called. a : 1, b : 0.000000 Order (1.100000, 1) based contructor called. a : 0, b : 1.100000 Type (int: 1) based contructor called. a : 1, b : 0.000000 Type (double: 1.100000) based contructor called. a : 0, b : 1.100000

Источник

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