Efficiency syntax for creating Java objects?

It may sound very simple. But I'm new to Java. With a few initial hours of training that I have included so far, I am constantly perplexed by the redundancy in the syntax of declaring a new object:

TypeName a = new TypeName(); 

In particular,

 String s = new String("abc"); Character c = new Character("A"); 

Why does anyone in the world want to type the TypeName keyword (e.g. String , Character , etc.) twice? I understand that there are short arms:

 String s = "abc"; char c = "A"; 

But these are more likely exceptions than rules. So can someone enlighten me please? thanks.

+7
java syntax
source share
9 answers

This is not at all redundant. There are two steps to using a variable:

  • Declaration : this step tells VM what will be a static consequence of the variable. For example: Object a; only visible space in the Object class will be displayed, and Integer b; will have all traces declared in the Integer class, and all inherited parent classes, until Object visible. This is for the static part.

  • instanciation : this step tells the VM what will be the dynamic trace of the variable. For example: List<String> c = new LinkedList<String>(); , then c.put("foo"); will use the LinkedList implementation of the put() method, even if the visible one is List::put() . Sometimes you need such a declaration / instanciation, but you will need to redefine access to a very specific method that does not appear with a static trace. For example, consider a method declared as public void method1(Object obj) , and you know that the obj instance is actually an Integer , so you will use a dynamic trace by introducing an object into it: int value = ((Integer) obj).intValue();

Now, for the part of String a = "A"; . Java has made an abbreviated notation of "primitive" classes available for simplicity. More specifically, starting with Java 1.5 you can do:

 Integer n1 = 1; Integer n2 = new Integer(1); // same thing int n3 = n2; 

And it works. But what's the difference? Consider this piece of code:

 String a = new String("A"); String b = new String("A"); String c = "A"; String d = "A"; System.out.println("a:" + a.hashCode() + " = b:" + b.hashCode() + " == " + (a == b)); System.out.println("b:" + b.hashCode() + " = c:" + c.hashCode() + " == " + (b == c)); System.out.println("c:" + c.hashCode() + " = d:" + d.hashCode() + " == " + (c == d)); 

displays

 a:65 = b:65 == false b:65 = c:65 == false c:65 = d:65 == true 

Why? Since the JVM is trying to use memory as much as possible, and since a and b create new instances of String , they do not use the same memory space. However, c and d use constant string values ​​(this is a compiler optimization) and therefore point to the same String object.

+4
source share

Because sometimes you want to do something like:

 // Explicitly force my object to be null String s = null; 

or

 // Cast a child class to its parent MyParentClass mpc = new IneritedClassFromParent(); 

or

 // Store and access a concrete implementation using its interface ISomeInterface isi = new ConcreteInterfaceImplementation(); 

In other words, just because you declare a type for storage does not always mean that you want it to be initialized with a new instance of this class.

You can use a new instance of the child class when using inheritance or implementing an interface when using interfaces.

Or sometimes you can explicitly force something to be null and populate it later.

+19
source share

Using this syntax, you can easily create an object of type X and assign it to a variable of type Y :

 List<String> myList = new ArrayList<String>(); 
+5
source share

Why does anyone in the world want to enter the TypeName keyword (e.g. String, Character, etc.) twice?

Because you are doing two things:

  • Declare a variable of a specific type
  • Creating an object of a specific type

Two types are not necessarily the same, for example

 Map m = new HashMap(); 

You are probably used to “dynamically typed” languages, such as PHP, where variables have no type. The advantage you get with Java static type declarations is that the compiler detects a lot of programming errors (even in the modern IDE when you type). For example, if you make a mistake:

 m.siez(); 

The compiler will immediately warn you that something is wrong with your program - and this can only be done because it knows that the declared Map type does not have the siez() method.

Some modern statically typed languages, such as C # and Scala, use the output type to give you the "best of both worlds", where you can omit the type declaration and the compiler assumes that it matches the type of object that you assign to it. However, such languages ​​always allow declarations of an explicit type, because type inference is not always possible or desirable (for example, in the example above, where the variable should use an interface rather than a specific class).

+5
source share

A lot of good answers are here why this is necessary. You are right that this often seems redundant. java is often (not unfairly) criticized as a bit, er ... verbose. There are several shortcuts. for example, for String s="Abc" strings (actually not a shortcut, it is slightly different and better because you are not explicitly creating a new object). There will also be some reduction in duplication in ads in java 7 for generics.

+1
source share

This is because there is no implicit way to assign the value of a complex object.

When you execute int a = 3; or double b = 2.5; , you can indirectly specify the type on the right side.

In OOP, you need to use a constructor, so you need to make new TypeName() . It also gives you the ability to pass parameters to customize the object.

Another reason is the use of interfaces. So you can do:

 MyInterface blah = new InterfaceImplementation(); MyInterface bar = new AnotherInterfaceImplementation(); 

and even:

 ParentClass foo = new DerivedClass(); 

This is due to the fact that when working with interfaces, you usually do not want to set the type of a variable as an implementation of the interface, but the interface itself. Otherwise, there would be no way to indicate which implementation to use.

Another useful thing is generics:

 List<SomeType> myList = new ArrayList<SomeType>(); 

Java 7 will simplify this for

 List<SomeType> myList = new ArrayList<>(); 

so you don’t have to type <SomeType> twice (this is especially painful in Maps).

0
source share

When you go to universal classes (extensions):

 class a extends b 

You will see that you can do something like this:

 b=new a(); 
0
source share

Well, the variable must be of type. And when you instantiate the object, you need to specify what type it should be. And, of course, they should not be the same. For example, you can set String for the variable Object. Of course, you might have something similar to make things a little easier:

 var s = new TypeName(); 

How it was done in C #. But I believe that in Java they did not see the need for this.
I agree that Java is pretty verbose by modern standards, but it's also quite easy to read, and not much syntactic sugar to embarrass you.

0
source share

There are strongly typed languages ​​that support "type inference" (for example, Scala). Java is simply not one of them (although there will be some type of output of common arguments in Java 7). In these languages, although a variable type is not declared, the compiler can unambiguously output it and still detect type errors. For example (non-Java):

 val str = "This is not a number!"; val x = str.intValue(); // Compiler error, because str is implicitly a String. 

There will be many cases in Java when you assign a specific concrete type on the right to a more general type on the left. For example:

 Set students = new TreeSet(); 

This is a good style, because your code will not be implementation specific. If you need to switch implementations (for example, you need faster search queries from the hash version of Set ), only the right side of the initializer is changed.

For this reason, it is especially important to declare public APIs using the correct abstractions rather than specific types.

0
source share

All Articles