What does this function do in Java? - java

public class TransparentProxy {
private static ProxyServer _proxyserver = null;
private static TransparentProxy _instance = null;
public TransparentProxy() {
}
public static void main(String args[]) throws Exception {
TransparentProxy.getInstance();
}
I understand everything except the public TransparentProxy() {}. Why is it empty? What is its purpose? Why is it exempt from having a return type?
I have looked it up but can't get an exact answer. Thanks

From the tutorial of the initial part of - Learning the Java Language
A class contains constructors that are invoked to create objects from the class blueprint.
Constructor declarations look like method declarations—except that they use the name of the class
and have no return type.
You don't have to provide any constructors for your class, but you must be careful when doing this.
The compiler automatically provides a no-argument, default constructor for any class without
constructors. This default constructor will call the no-argument constructor of the superclass.
It looks like you've not read through the basics of Java language yet, you should go through them.

This is an empty constructor. It has no return types and named as the class name.
An empty constructor is needed to create a new instance via reflection by your persistence framework. If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default.

public TransparentProxy() {} ---is a Constructor
Java constructors are the methods with the same name as the Class with no return type/value. They are called or invoked when an object of class is created and can't be called explicitly. An object of a class is created using the new keyword. Ex: TransparentProxy proxy = new TransparentProxy();
Three types of Constructors are present.
1. Default Constructor
JVM internally declares a constructor when no constructor in specified. This is to allow a class to create an instance of it. Also, an Interface in Java does not have a constructor and hence no instances/object can be created.
2. Zero argument Constructor
A constructor defined with no arguments is called a Zero argument Constructor. You may use it to initialize variables to some value to begin with. All objects/instances of the class will have the same initial values.
3. Constructor with arguments
Its a constructor defined with arguments which initialize the variables of the class at the time of object creation. Every object/instance created of that class will have different initial values depending on the values passed to the constructor.
A constructor can be overloaded with different type of arguments or the number of arguments.
It cannot be overrided in a sub class.
Read here -- Why do constructors not return values?

Related

Do I need to always create a constructor for objects in Java?

I have seen a lot of code that doesn't refer to any constructors. I have created code that doesn't contain constructors which seemingly defies the point of having one. Are there rules for when one needs to implement a constructor?
You don't have to provide any constructors for your class, but you
must be careful when doing this. The compiler automatically provides a
no-argument, default constructor for any class without constructors.
This default constructor will call the no-argument constructor of the
superclass. In this situation, the compiler will complain if the
superclass doesn't have a no-argument constructor so you must verify
that it does. If your class has no explicit superclass, then it has an
implicit superclass of Object, which does have a no-argument
constructor.
As provided by the javaOO documentation
If you have a class "A", and you don't create a constructor, a constructor:
public A(){
}
will be implicitly created, i.e. you won't actually see it. (thanks, #Steve Smith)
If you create any constructor, this default constructor will not be created. This is important when using certain design patterns like factory method and singleton.
If you create a private constructor:
private A(){
}
the default constructor (that is public) will not be created. This means that only inside the class A you can create instances of A. To export instances of A to other classes, you need to create them on static methods and return the references. This is employed on the Singleton pattern, for instance:
public A{
private static A instance = new A();
public static A getInstance(){
return instance;
}
//the default public constructor will not be created
private A(){
}
}
To answer your question, you HAVE to provide a constructor if you want to ensure that the instantiated object is initialised with certain data. For example, you might want to have a Person class which always has a valid first & last name as well as an age.
Person hugo = new Person("Hugo", "First", 25);
the constructor would then be
public Person(String first, String last, int age) {
setFirst(first);
setLast(last);
setAge(age);
}
protected Person() {}
This way it is impossible to instantiate an empty Person.

What does the default constructor really do? [duplicate]

This question already has answers here:
What is the actual use of the default constructor in java?
(7 answers)
Closed 4 years ago.
There is something that I don't understand about the real role of the default constructor in java. In the official tutorial about object creation :
Creating Objects
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.
And in the docs about the Default Constructor (§8.8.9)
8.8.9. Default Constructor
If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
So even the default constructor of the class Object has an empty body. And I know that the default constructor does NOT initialize fields to their default values, because it's the compiler who does that :
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler.
What I don't understand is, if we didn't declare a constructor, what does the default constructor really do ?
what does the default constructor really do?
It calls super(). As per all your quotations. And does nothing else. JLS #8.8.9:
If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
i.e. it does nothing else. For those who believe it initializes instance variables please see JLS #12.5 where the contrary is asserted.
In Java, if you don´t declare any constructor the compiler create a default constructor and this constructor call to super() method, that is parents constructor. And in this process, inits instance variables like no-default constructors.
What I don't understand is, if we didn't declare a constructor, what
does the default constructor really do ?
By default, if no constructor is declared, a class has a default constructor with no args. I think that's why, by default all constructor calls super(). It follows probably the convention over configuration principle.
Whatever you declare a public constructor or you don't declare at all constructor, first instruction of the constructor is super().
That's why if you define in a class MyClass a constructor with args MyClass(String s) without keeping a constructor with no argument, constructor of MyClass subclasses cannot compile while it doesn't precise in their first instruction, the call to an existing parent constructor, in the exemple, it would be super(String ...).
Here an example :
public class MyClassWithNoArg{
public MyClassWithNoArg(){
}
}
MyClassWithNoArg constructor calls super() in this first instruction even if it not specified in the source code.
It is as if it is written in this way :
public class MyClassWithNoArg{
public MyClassWithNoArg(){
super();
}
}
Imagine now another class MyClassWithArg:
public class MyClassWithArg{
public MyClassWithNoArg(String s){
}
}
And MySubclass a subclass of MyClassWithArg
public class MySubclass extends MyClassWithArg{
public MySubclass (String s){
}
public MySubclass (){
}
}
In both cases, it will not compile since as explained previously all constructors call by default the default constructor (super()) of their parent but here the parent,MyClassWithArg, has no constructor with no arg. So, it doesn't compile.
So to solve the problem, you have to call the super constructor which exists.
public class MySubclass extends MyClassWithArg{
public MySubclass (String s){
super(s);
}
public MySubclass (){
super("");
}
}
Now, compilation is OK.
Without constructor no one can create a object of a class. Now if programmer does not add any constructor with a class then java compiler added a constructor with that class before compilation,which is known as default constructor in java.
But if programmer adds any kind of constructor(with argument or without argument) then that becomes user defined constructor and no constructor 'll be added via java compiler.
Now question is what does constructor do.
allocates memory for new object
if user defines any other operation like initialising variable that is done.

Java - Is it possible to write public void() in Constructor?

I couldn't find information if it is possible to write public void in constructor section. Is it possible?
At the byte code level, a constructor is always void so it would be redundant to specify it. i.e. the constructor is always called <init>V i.e. the V is the return type where V == void. Similarly the static initialiser is <clinit>V You will see this notation if you take a stack trace (e.g. print an exception) while in these methods.
The constructor actually takes the object to be initialised as an argument as the object is created before calling the constructor. Note: you can create the object without calling a constructor with Unsafe.allocateInstance(Class)
I couldn't find information if it is possible to write public void in constructor section. Is it possible?
It is not possible to write it as Java distinguishes a constructor from a method is that it must have the same name as the class, and it must not specify a return type. If you specify a return type, it assumes it's a method.
The notation x = new Clazz() also limits the number of return values to 1 which is the object. There is no easy way to modify this notation to return more than one object. i.e. supporting a return type for constructors would not be easy.
If you want to define a return type, most likely you are thinking of a factor method like this.
public static MyInterface createObject() {
return new MyClass();
}
Note how the return type is different to the class actually created, but there is still only one reference returned.
The constructor syntax is defined in the Java Language Specification. Anything else is incorrect.
The question is unclear. Peter Lawrey answered one interpretation, this is an answer to another.
You cannot declare methods within a constructor. You can, however, declare a class and declare variables.
Because you are able to declare a class within a constructor, you could declare a method inside of a class and then use the class. If the method isn't static you can construct an object of the class.
No, Java only allows a method to be declared within a class, not within another method or constructor.Indirectly you can do something like this :
public A() {
class B {
public void m() {
}
}
}

Default constructor in Java?

What is the purpose of the default constructor in java
class Bike1 {
Bike1() {
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.
Your example provides a constructor,
Bike1(){System.out.println("Bike is created");}
which means you do not get a default constructor. A default constructor is inserted if you do not provide any constructor. Finally, Bike1 is a no-args constructor with package level (or default) access permission and appears to display a message when an instance of Bike1 is created.
Default constructor means that when you don't create any constructor for your class, the compiler automatically creates a default constructor (with no parameters) to your class at the time of compilation.
In your example you created a constructor. The constructor does not create any objects, it initialize the object.
Default constructors allow you to create objects with known, default settings and behavior. If you call a constructor with arguments, you are creating a custom object. But calling the default constructor will create objects with identical properties every time it is used.
Typically, a default constructor with "no code" doesn't need any code; it already has all the information it needs to create the object.
Remember that default constructor and a constructor with no-args are different.
Since you are defining a constructor Bike1(){} here, the default constructor will loose it's scope and will not be generated automatically.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. It initialises any uninitialised fields to their default values...
follow this link.. Java default constructor
Default constructor have no arguments(parameters) and constructor name is same as class name.It will invoke at the time of object creation.
Example:
class Display{
Display(){
System.out.println("Default Constructor");
}
}
class constructor{
public static void main(String args[]){
Display dis=new Display();
}
}
Output:
Default Constructor
Because when the time of object creation default constructor will invoke automatically.
First thing we need to know that default constructor and no argument constructor are both different things. The no argument constructor is one which we declare inside the class where we actually may or may not write the functionality. The default constructor is one which will be called after object creation. The main purpose of this is to initialize the attributes of the object with their default values.
Java compiler provides a default constructor by default if there is no constructor available in the class

How to choose which constructor to use and what class does the Class<?> type belongs to

I have a class in which i have intialized hashmap in static block. Passing the key, I have retrived the value which is a class. In order to create object for this class. I have used the constructor class to get the constructor and passed arguments and created object.
I have two class in hashmap. To create objectfor EchoExpression I need to pass two arguments and for OutExpression class i need to pass only one argument(String).
Based on the class returned by the key I need to execute which constructor to get and implement, whether the constructor with one argument or two argument.
In EchoExpression, the constructor contains two arguments.
eg:
JXPathExpression check = new JXPathExpression(String expression, Class<?> type)
String belongs to String.class but what class does the Class type argument belongs too? so that i can use it in getting the constructor
public class ExampleFactory {
private static HashMap<String,Class<?>> hmap = new HashMap<String,Class<?>>();
static
{
hmap.put("echo", EchoExpression.class);
hmap.put("Out", OutExpression.class);
}
public void getExpo(String key,String expression)
{
Class aClass =map.get(key);
//Constructor implementation for OutExpression where only one argument string is passed
Constructor constructor = aClass.getConstructor(new Class[]{String.class});
Object object= constructor.newInstance(expression);
//Need constructor for passing two arguments string and class<?> for EchoExpression
return null;
}
}
For such a thing you should in all cases try to have unified constructor parameters or a way to store the parameters per class.
Now for your questions. Class<?> is a reference to a unknown class. Basically to any class. When using it its more or less equal to Class<Object> because all classes got Object as parent.
For using constructors with multiple arguments you first need to fetch the fitting constructor. At this point its already possible to fetch errors that happen in case the class does not support instances with this configuration of arguments.
Fetching the constructor works this way:
aClass.getConstructor(new Class[]{String.class, Object.class, ...});
This works with as many argument types as you like. Creating the new instance of the class then works this way:
constructor.newInstance(theString, theObject, ...);
The function newInstanace is implemented as many arguments as needed. So depending on how many arguments the constructor that was requested requires the newInstance function will be able to work with it.
For all what you intend... maybe a proposal: Maybe its a option not to load the new objects using reflection but rather by storing instances of those objects and returning copies of the objects created using copy constructors or the clone method. In many cases this is less difficult to get running.
Maybe what you are looking for is Class.class like in:
Constructor constructor = aClass.getConstructor(new Class[]{String.class, Class.class});

Categories

Resources