Different ways to create an object in Java

Different ways to create an object in Java

You must have used the “new” operator to create an Object of a Class. But is it the only way to create an Object?

Simple Answers is NO, then in how many ways we can create Object of a Class. There are several like

  • Using New keyword
  • Using New Instance (Reflection)
  • Using Clone
  • Using Deserilization
  • Using ClassLoader
  • … don’t know 

Now we will explore the different ways of creating the Object except new Operator.

Using New Keyword

Using new keyword is the most basic way to create an object. Use new keyword to create and Object of class.

1

2

3

4

5

6

7

8

9

10

11

12

13

public class ObjectCreationExample {

public static void main(String[] args) {

// Here we are creating Object of JBT using new keyword

JBT obj = new JBT();

}

}

class JBT{

String Owner;

}

Using New Instance (Reflection)

Have you ever tried to connect to any DB using JDBC driver in Java, If your answer is yes then you must have seen “Class.forName“. We can also use it to create the object of a class. Class.forName actually loads the class in Java but doesn’t create any Object. To Create an Object of the Class you have to use newInstance method of Class class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

/*

* Here we will learn to create Object of a class without using new Operator.

* But newInstance method of Class class.

*/

class CreateObject {

public static void main(String[] args) {

try {

Class cls = Class.forName("JBTClass");

JBTClass obj = (JBTClass) cls.newInstance();

JBTClass obj1 = (JBTClass) cls.newInstance();

System.out.println(obj);

System.out.println(obj1);

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

}

}

}

class JBTClass {

static int j = 10;

JBTClass() {

i = j++;

}

int i;

@Override

public String toString() {

return "Value of i :" + i;

}

}

Note*: If you want to create Object in this way class needs to have public default Constructor.

Using Clone

We can also use Clone() method to create a copy of an existing Object.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

/*

* Here we will learn to create an Object of a class without using new Operator.

* For this purpose we will use Clone Interface

*/

class CreateObjectWithClone {

public static void main(String[] args) {

JBTClassClone obj1 = new JBTClassClone();

System.out.println(obj1);

try {

JBTClassClone obj2 = (JBTClassClone) obj1.clone();

System.out.println(obj2);

} catch (CloneNotSupportedException e) {

e.printStackTrace();

}

}

}

class JBTClassClone implements Cloneable {

@Override

protected Object clone() throws CloneNotSupportedException {

return super.clone();

}

int i;

static int j = 10;

JBTClassClone() {

i = j++;

}

@Override

public String toString() {

return "Value of i :" + i;

}

}

 Note*:

  • Here we are creating the clone of an existing Object and not any new Object.
  • Clone method is declared protected in Object class. So it can be accessed only in subclass or in same package. That is the reason why it has been overridden here in Class.
  • Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.

Using Object Deserialization

Object deserialization can also be used to create an Object. It is just the opposite of serializing an Object.

Using ClassLoader

We can also use Class Loader to create Object of a Class. This way is some what same as Class.forName option.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

/*

* Here we will learn to Create an Object using Class Loader

*/

public class CreateObjectWithClassLoader {

public static void main(String[] args) {

JBTClassLoader obj = null;

try {

obj = (JBTClassLoader) new CreateObjectWithClassLoader().getClass()

.getClassLoader().loadClass("JBTClassLoader").newInstance();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

System.out.println(obj);

}

}

class JBTClassLoader {

static int j = 10;

JBTClassLoader() {

i = j++;

}

int i;

@Override

public String toString() {

return "Value of i :" + i;

}

}

时间: 2024-10-13 05:41:13

Different ways to create an object in Java的相关文章

php错误:Uncaught exception com_exception with message Failed to create COM object

本文为大家讲解的是php错误:Uncaught exception com_exception with message Failed to create COM object,感兴趣的同学参考下. 错误: Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `InternetExplorer.Application': 拒绝访问 在PHP中调用IE使用如下代码: br

instanceof,Object.getPrototypeOf(),Object.create(),Object.setPrototypeOf(),Object.prototype.isPrototypeOf(),Object.prototype.__proto__

一.instanceof instanceof运算符返回一个布尔值,表示指定对象是否为某个构造函数的实例 var v = new Vehicle(); v instanceof Vehicle // true instanceof对整个原型链上的对象都有效,因此同一个实例对象,可能会对多个构造函数都返回true var d = new Date(); d instanceof Date // true d instanceof Object // true 利用instanceof运算符,还可以

Cause: org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: java.sql.SQLException: 不支持的特性

mybatis插入数据时报错: Cause: org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: java.sql.SQLException: 不支持的特性 at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFacto

将Object转换成List<?>,避免Unchecked cast: 'java.lang.Object' to 'java.util.List<java.lang.String>'

java中如果需要将一个object转成list,大部分人会直接使用强制类型转换:(List<String>) obj这样.这样强制转换编译会提示Unchecked cast: 'java.lang.Object' to 'java.util.List<java.lang.String>',编译器的意思该强制类型转换并未做类型校验,强制转换并不安全,可能会抛出异常导致程序崩溃.在很多博客中有人会建议用@SuppressWarnings("unchecked")解

Creating InetAddress object in Java

I am trying to convert an address specified by an IP number or a name, both in String (i.e. localhost or 127.0.0.1), into an InetAdress object. There's no constructor but rather static methods that return an InetAddress. So if I get a host name it's

Create Excel file in java using PoI

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 8

Android 执行 gson.toJson(object) 报java.lang.StackOverflowError异常

如下面的代码,执行后报java.lang.StackOverflowError错误: MusicSavedInfo musicSavedInfo=new MusicSavedInfo(currentStartTime,openOrCloseFlag,currentDayFlags,currentSelectMusicTitle,currentSelectMusicPath,"1"); String jsonData=gson.toJson(musicSavedInfo); 我手机4.1

包装类、Object类——Java笔记(八)

包装类: 基本数据类型的包装类 基本数据类型 包装类 byte Byte short Short int Integer long Long char Character float Float double Double boolean Boolean 基本数据类型包装类除了Character类之外,其他7个都有两个构造方法 一个构造方法传参传的是基本数据类型本身 另一个构造方法传参传的是String类型的,而Character少的就是这一个,即public Character(String

005 The Object in JAVA

大家都知道,JAVA是面向对象的开发语言.在JAVA中,一切东东都由类和对象承载.其中,类是一个抽象的概括(eg:person.animal.book等等),而对象是由类构造的(eg:Person p =new Person(),这里p就是一个对象),对象持有数据状态,而类没有,我们可以把类看成类似孵化器的东西,当我们需要使用类承载数据或使用类中的方法时,我们可以使用我们想用的类构造出我想要的对象,然后使用这个对象.对象所持有的数据状态通常是变量,我们称之为成员变量.成员变量是和对象是保存在一起