constructor in java_Constructors in Java_尾崎秀実的博客-程序员宅基地

技术标签: constructor in java  

Java constructorsare special methods (without return type) which allow you to fully initialize the object state before it can be used by other classes inside application. Constructors in java are invoked using new

keyword.

Let’s learn about constructors in more depth.

What are Constructors in Java

Constructors are special method like (no exactly methods) constructs which helps programmer in writing object initialization

code, before the object is available for use by other objects in the application.

Whenever application needs a new instance of any class, JVM allocates a memory area inside heap. Then JVM executes the invoked constructor (class can have multiple constructors) and initialize the object state. Inside constructor, you can access all object attributes and assign them to their default values or any desired values.

Read More:Java Memory Model

Types of Constructors

Default Constructor (no-arg constructor)

In case, programmer does not provide any constructor in class definition – JVM provides a default constructor to the class in runtime.

Programmer also can override default constructor in class. Let’s look at the syntax.

public class Employee

{

public Employee() {

}

}

In default constructor, name of the constructor MUST match the class name and it should not have any parameters.

Parameterized Constructor via Constructor Overloading

As stated above, there can be multiple constructors inside a class. This is possible by having overloaded constructors. In constructor overloading

, you can pass list of arguments as per requirements i.e. how many ways a class can be initialized.

public class Employee {

private String firstName;

private String lastName;

public Employee() {//constructor 1

}

public Employee(String firstName) { //constructor 2

}

public Employee(String firstName, String lastName) { //constructor 3

}

}

In above class, we have defined 3 constructors to handle 3 situations – how the employee object might be required to create by the application i.e. without name, with first name only and with first and last name both.

Employee employee1 = new Employee();

Employee employee2 = new Employee("Lokesh");

Employee employee3 = new Employee("Lokesh", "Gupta");

Constructor Rules

There are few mandatory rules for creating the constructors in java.

Constructor name MUST be same as name of the class.

There cannot be any return type in constructor definition.

There cannot be any return statement in constructor.

Constructors can be overloaded by different arguments.

If you want to use super()

i.e. super class constructor then it must be first statement inside constructor.

Constructor Chaining

In java, it’s possible to call other constructors inside a constructor. It’s just like method calling but without any reference variable (obviously as instance is fully initialized as of now).

Now we can call constructors of either same class or of parent class. Both uses different syntax.

Call same class constructor

To call other constructors from same class, use this

keyword. For example,

public Employee() {

}

public Employee(String firstName) {

this();//calling default constructor

}

public Employee(String firstName, String lastName) {

this(firstName);//calling constructor with single argument of String type

}

Call super class constructor

To call constructors from super or parent class, use super

keyword. The usage of super keyword is similar to this

keyword – only difference is that super

refers to super class and this

refers to current instance.

public Employee() {

//refer to Object class constructor

//as it is parent class for every class

super();

}

Private Constructors

Sometimes you want to protect the constructor from being called by other classes. Altogether you want that nobody should be able to create a new instance of the class.

Why anybody would want that? Well, it’s necessary forsingleton pattern. In singleton, an application wants to have one and only one instance of any class.

A common singleton class definition looks like this:

public class DemoSingleton implements Serializable

{

private static final long serialVersionUID = 1L;

private DemoSingleton() {

// private constructor

}

private static class DemoSingletonHolder {

public static final DemoSingleton INSTANCE = new DemoSingleton();

}

public static DemoSingleton getInstance() {

return DemoSingletonHolder.INSTANCE;

}

protected Object readResolve() {

return getInstance();

}

}

That’s all about constructors in java

. Drop me your questions in comments section.

Happy Learning !!

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30676505/article/details/114978349

智能推荐

回传值_sunyushen01的博客-程序员宅基地

//回传   huichuan.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String backStr="亲,我是回传值喔";Intent intent=getIntent();intent.putExtra("HUI", backStr);

wget不起作用_haohaounique的博客-程序员宅基地_wget没反应

解决方法:1. 理解NAT,桥接,仅主机 三种模式 参考文章https://blog.csdn.net/zkuncn/article/details/78452098ping各自ip看是否联通 ping外网地址看是否联通2.设置镜像源 下载镜像源文件--->替换 yum clean all yum makecache3.yu...

php去除某个超链接,PHP正则表达式移除超链接文本_weixin_39856607的博客-程序员宅基地

有些时候,我们需要对一些html文本进行处理,比如需要将文本中的超链接内容去除,这个时候就需要用到正则表达式了。比如你可以用$str = preg_replace("/]*href=[^>]*>|[^a]*a[^>]*>/i","",$strhtml); 这段来实现需求,如果想要更多解决方法,可以参看以下的。1、删除内容中的超链接ereg_replace(']*)>(...

物联网应用技术竞赛——android笔记__siyu_的博客-程序员宅基地

Android笔记1.格式化字符串 double a=26.54578; DecimalFormat df = new DecimalFormat("#.00"); //保留小数点后两位 double temp=df.format(a);2.导入摄像头包时需要加以下代码sourceSets { main { jniLibs.srcDirs = ['libs'] }}3.Android透明度android:alpha="0.5"4.android展

coffee后台打印___星期一__的博客-程序员宅基地

后台打印#20181010 auth://funny.coffeeclass Funny @dog : ()-> console.log " ii. ;9ABH, " console.log " SA391, ...

美国大学计算机专业怎么留学校,在美国大学计算机专业哪所院校好?_weixin_39966020的博客-程序员宅基地

在美国大学计算机专院校推荐:1 Carnegie Mellon University 卡内基梅隆大学1 Massachusetts Institute of Technology 麻省理工学院1 Stanford University 斯坦福大学1 University of California -Berkeley 加州大学伯克利分校5 Cornell University 康奈尔大学5 Uni...

随便推点

C语言中qsort()库函数的排序应用_KID怪盗基德1412的博客-程序员宅基地

C语言中不像C++一样有sort(arr.begin(),arr.end(),cmp)排序接口,但是也提供类似的库函数。1. 首先要包含头文件<stdlib.h>2. 对于一维整型数组函数指针定义:int cmp_int(const void *a, const void *b) { int *_a = (int *)a; int *_b = (int *)b; return *_a - *_b;}main函数调用:int main(){

UVA514-Rails_u小鬼的博客-程序员宅基地

UVA514-RailsThere is a famous railway station in PopPush City. Country there is incredibly hilly. The stationwas built in last century. Unfortunately, funds were extremely limited that time. It was possible toestablish only a surface track. Moreover, it

linux 驱动入门 魏清,Linux下的SPI总线驱动(三)_梁航铭的博客-程序员宅基地

版权所有,转载请说明转自原创作者:南京邮电大学 通信与信息系统专业 研二 魏清五.SPI测试代码对于SPI总线驱动,我们可以分为SPI控制设备驱动和SPI接口设备驱动。而作为驱动开发人员主要是像SPI移植的时候一样会添加SPI控制设备和SPI接口设备的私有数据,同时驱动开发人员还需要会开发SPI接口设备驱动,而我们这个SPI测试实验中,我们使用的是内核自带的SPI接口设备驱动代码spidev.c...

Ceph 定制crush map_weixin_33704591的博客-程序员宅基地

定制化crush map简单实验首先,查看原始osd目录树[[email protected] ~]# ceph osd tree# id weight type name up/down reweight-1 3.24 root default-5 1.08 rack rack1-2 1.08...

机器学习-python基础_Pikachu_simple的博客-程序员宅基地

# -*- coding: utf-8 -*-"""Created on Sun Dec 22 10:15:39 [email protected]: zhh"""import math'''1、基本语法'''#同行显示多行语句:用";"分号隔开#print输出:#print默认换行,若要 不换行在变量末尾加上逗号,end=''x='a';y='b'print(x,end='') #...

MySQL系列:性能监控常用4大语句_NIO4444的博客-程序员宅基地

#查看动态指标 show global STATUS; >>MySQL系列:show Global STATUS 用法#查看精通参数 show global variables;>>MySQL系列:show Global VARIABLES 用法#查看连接进程 show full processlist; >>MySQL系列:show full PROCESSLIST 用法#查看同步状态 show slave ST...

推荐文章

热门文章

相关标签