Is there any way to directly accept values for an object in Java?
In Dart this is how I would do it.
class Nice
{
String hello;
Nice(this.hello);
}
Is there some similar way in Java?
Is there any way to directly accept values for an object in Java?
In Dart this is how I would do it.
class Nice
{
String hello;
Nice(this.hello);
}
Is there some similar way in Java?
You should take in consideration de OOP Concept "ENCAPSULATION" This concept is also often used to hide the internal representation, or state, of an object from the outside. This is called information hiding. The general idea of this mechanism is simple. If you have an attribute that is not visible from the outside of an object, and bundle it with methods that provide read or write access to it, then you can hide specific information and control access to the internal state of the object.
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The main idea is that the member variable is private and can be accessed or modified through its GET and SET method.
This is possible in JAVA but you disrespect the concept presented above. What is happening here is that the member data has its "Access Modifier" as public and its value can be accessed.
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "Person1";
}
}
class Person {
public String name;
}
Visit
You can declare the field as public, then it is accessible from the outside:
public class A {
public String myField;
}
public class Runner {
public static void main(String[] args) {
A a = new A();
a.myField = "my cool value";
}
}
However, this is not the "java-way" of doing it, since it breaks encapsulation.
If you directly want to capture values for objects when they are initialized then make a constructor like:
class Nice {
String hello;
String greetings;
Nice(String hello, String greetings) {
this.hello = hello;
this.greetings = greetings;
}
}
Then create object by passing values directly like:
Nice nice = new Nice("hello", "Good Evening!");
The Java equivalent of that Dart class would be
class Nice {
private String hello;
public Nice(String hello) {
this.hello = hello;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
It is no more or less efficient than the Dart class.
There is no inherent performance efficiency in the way the Dart class is written that a Java compiler can't get out of the corresponding Java code. The Dart code is syntactically shorter, but that is all.