Why is java new?

Possible duplicate:
Why are C # and Java worried about the β€œnew” statement?

Why does java have a new keyword? To create an object of type A, I have to type A a = new A().

There is no stack distribution in Java, so why can't this be simplified to A a = A()?

+3
source share
6 answers

Because C ++ did it this way, I suppose. It was supposed that Java should look superficially, like C ++, but with a very simplified and simplified language.

Anyway you have a problem:

class Foo {
   private static void A() {
     System.out.println("method");
   }

   public static void main(String[] args) {
     A();
   }
}

class A {
  public A() {
    System.out.println("ctor");
  }
}

What is going to happen here? ctoror method?

+3
source

One obvious flaw in your syntax proposal is here:

class A {}

class B extends A {
    public A A() { return new B() }

    public A foo() { return A(); } //ERK            
}

foo? A() A.

, - , , :

public class A {
    public static A A() { return new A(); }
}

import static my.stuff.A.*

+2

, , .

+1

. Python Java, A(), .

0

Java , , , . A a = A();, A(). , Java , ... ( ), , Java "". , public A A() , .

0

, .

One reason is related to mixing auto-assignment objects (based on the stack) and placing heaps and links for them. Do you know how in C ++ you have to be careful not to point to an automatic variable? This is less of a headache to worry about.

The second reason is probably because Java is typically designed for low-cost allocation of objects and low-cost GC for recent objects (thanks to the use of collective garbage collectors). Therefore, there is no substantial benefit to supporting both types of distribution of objects.

0
source

Source: https://habr.com/ru/post/1785759/


All Articles