suppose i have classA and classB(generic), reference http://www.exampledepot.com/egs/java.lang.reflect/Constructors.html
I am passing a customobject from classA to classB, now i am wanting constructor of customobject in classB and call it
classA
customclass objCustomclass;
classB mClassB;
mClassB.getConstructorAndCall(objCustomclass);
classB
public void getConstructorAndCall(Object objCustomclass);
try {
Object filledObject = objCustomclass.getClass().newInstance();
// here i need to call filledObject's contructor
} catch (Exception e) { }
I am able to create object as the instance of custom object but what about constructor.
note: getConstructorAndCall() is a commom method and in that object is of unknown type that means any class can pass its object.
Thanks.
well if the constructor is empty, then I think that what you have should run the constructor. Anything more complicated, like, passing parameters to the function can be done through:
Constructor[] constructors = objCustomClass.getClass().getConstructors()
for (int i = 0; i < constructors.length; i++) {
Constructor c = constructors[i];
Class[] paramTypes = c.getParameterTypes();
Object[] params;
// do fancy stuff here - it helps if you know what the constructors take beforehand
Object filledObject = c.newInstance(params);
}
Constructor with parameters
From the JavaDoc for java.lang.Class ( http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#newInstance() ):
Creates a new instance of the class represented by this Class object.
The class is instantiated as if by a new expression with an empty
argument list. The class is initialized if it has not already been
initialized.
I. E. the newInstance() method always uses the default constructor.
Most times I see people using new instance and requiring a particular constructor or signature, it happens to be due to a lack on the solution design. You might want to double check if a pattern applies to the solution you need.
Related
Begining Java
Can someone break down whats going on here
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[] {
WebApplicationContextConfig.class
};
}
My understanding is that this is a method which expects its return to be an array of Class object of an unknown type
But what is the return?
An instantiation of an anonymous Class object array without a constructor and its implementation block at the same time?
What's the name of this for further reading and I can't seem to find this subject area?
There is no anonymous Class object. Class is a java class like any other, but with a name that is bound to confuse Java beginners.
the statement
return new Class[] {
WebApplicationContextConfig.class
};
is equivalent to
Class [] result = new Class[1];
result[0] = WebApplicationContextConfig.class;
return result;
WebApplicationContextConfig.class is called a class literal, and here is a some discussion about them.
It is an array declared with default values. In Java it is short-hand way of making arrays.
String[] names = {"Arvind","Aarav"}; // initialization
Now to re-assign a completely new array.
names = new String[]{"Rajesh","Amit","Mahesh"}; //re-initalization
Same thing with methods, let us say, returning days of week
public String[] weekdays(){
String[]days={"Sun","Mon","Tue"};
return days;
}
OR
public String[] weekdays(){
return new String[]{"Sun","Mon","Tue"};
}
Now about Class[], for type Class possible value is null and SomeClassName.class.
Class stringClass = String.class;
Class[] moreClasses = {Long.class, Boolean.class, java.util.Date.class};
It's just declaring an Array of Class and initialize it with one element (The Class definition of WebApplicationContextConfig)
It is array of wildcard type. See this for more
This is an array initializer. When you say
new Something[] { x1, x2, x3 }
it creates a new array of the Something class, and initializes the values to whatever you tell it in the curly braces. The length of the new array is the number of values.
I think you might be confusing it with a very similar syntax:
new Something() { class declarations, method overrides, etc. }
This one creates an anonymous subclass of Something, and it's used a lot for creating anonymous subclasses that implement interfaces. It's not at all related to the array initializer syntax, even though the appearance is pretty close.
We have parent class and child class having common method testparent() but there is difference in parameters
//Parent Class
public class Overriding {
int a,b,c;
//Parameters are different in number
public void testParent(int i, int j) {
System.out.println(a+b);
}
}
//Child Class Extending Parent Class Method
class ChildOverriding extends Overriding {
int c;
public void testParent(int i,int j,int k) {
System.out.println(a+b+c);
}
//Main Is not getting executed????
public static void main(String args[]) {
Overriding obj = new ChildOverriding();
obj.testParent(1,4,8);
}
}
}
Overriding Means sub class should have same signature of base class method.
Parameters and return type should be the same.
Actually your problem here is that you're accessing a method from SubClass over a reference object of a SuperClass.
Let me explain little bit more.
Super obj = new Sub();
This line will create one reference variable (of class Super) named obj and store it in stack memory and instance of new Sub() with all implementation details will be stored in heap memory area. So after that memory address of instance stored in heap is linked to reference variable stored in stack memory.
obj.someMethod()
Now when we call any method (like someMethod) on reference variable obj it will search for method signature in Super class but when it calls implementation of someMethod it will call it from instance stored in heap memory area.
That's the reason behind not allowing mapping from Super to Sub class (like Sub obj = new Super();) becuase Sub class may have more specific method signature that can be called but instance stored in heap area may not have implementation of that called method.
So your program is giving error just because it isn't able to find method signature that you're calling in super class.
Just remember Java will always look for method signature in type of reference object only.
Answer to your question is Yes, we can have different number of parameters in subclass's method but then it won't titled as method overloading/overriding. because overloading means you're adding new behaviour and overriding means changing the behaviour.
Sorry for my bad English, and if I'm wrong somewhere please let me know as I'm learning Java.
Thanks. :)
You can have the two methods, but then the one in ChildOverriding are not overriding the one in Overriding. They are two independent methods.
To fix your compilation problem, you have to either declare obj ChildOverriding
ChildOverriding obj = new ChilOverriding();
or you have to also implement a three-argument method in Overriding
How to call the Constructor multiple times using the same object
class a
{
a(int i)
{
System.out.println(i);
}
public static void main(String args[])
{
a b = new a();
int x = 10;
while( x > 0)
{
//Needed to pass the x value to constructor muliple times
}
}
}
I needed to pass the parameter to that constructor.
Constructor of a class A constructs the objects of class A.
Construction of an object happens only once, and after that you can modify the state of the object using methods (functions).
Also notice if programmer does not write any constructor in his class then the Java compiler puts the constructor for the class (public constructor without any parameters) on its own.
In the case where a constructor has been provided by the programmer, the compiler does not create a default constructor. It assumes, the programmer knows and wants creation of the objects of his/her class as per the signature of the explicit constructor.
Constructor calls are chained. Suppose there exists below class relationship.
Child.java extends Parent.java and Parent.java extends GrandParent.java.
Now if Child child = new Child(); is done, only one object is created and that is of Child.java, but the object also has all of the features of GrandParent first then with the features of the Parent and then the Child.
Hence first constructor of GrandParent.java is called then Parent.java is called and lastly the constructor of Child.java is called.
Constructors are special and different from other methods.
The intent of constructors is to create the object, so each time you use the new operator, the constructor is called and a new object is created. You can not call the constructor directly. You need the new operator to call it. Even if you see some class defining methods like getInstance(), it still uses the new operator to construct the object and return the created object.
*PS there are ways to create an object without calling constructor (like Serialization) but that is out of context of the discussion here.
Constructors are called only once at the time of the creation of the object.
Can you please be specific about what you want to achieve?
But I think you could try one of the following two things.
Calling the constructor to create a new object and assigning it to the object 'b':
b = new a(1);
Using the setter method:
void setI(int i){
this.i = i;
}
b.setI(1);
int x = 10;
while( x > 0)
{
a b = new a(x);
}
So I was watching a youtube video and the youtuber said: "When you are creating 'this' object, you are going to need to set it to a new ' type ' of this object"...
The class was called objectIntro and the constructor was:
public objectIntro(){
//Object Constructor (Method)
}
So here's my question...
I tried to create an object which basically tells me about the level of petrol with in a car...
public class car {
double petrolLevel;
double tankSize;
public void refillPetrol(double I){
if(I>tankSize){
I = tankSize;
petrolLevel = petrolLevel + I;
}
else{
petrolLevel = petrolLevel + I;
}
}
public void fuelConsumption(double O){
if(O>tankSize){
O=tankSize;
petrolLevel = petrolLevel - O;
}
else{
petrolLevel = petrolLevel - O;
}
}
public String returnPetrolLevel(){
return String.format("%sL", petrolLevel);
}
}
Then the class in which the object is created is...
public class carObject {
public static void main(String[] args){
car object1 = new car();
object1.tankSize = 50;//Litres
object1.petrolLevel = 0;
object1.refillPetrol(50);
object1.fuelConsumption(20);
object1.returnPetrolLevel();
System.out.printf("Petrol Level: %s", object1.returnPetrolLevel());
}
}
My question is, how come my object works without a constructor?
In the car class, I do not have a method which says "public car(){
}", whereas the youtuber stated this would be required?
Could someone clear this up, also I think I am not using the term constructor and method in the write context, could someone explain the definition of these terms, along with some examples.
Thanks
It's all in the Java tutorial
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.
Also the convention is to uppercase your class names, lowercase your method parameters and use getters/setters for member variables which usually are private.
Sometimes you actually might notice that you cannot do new MyClass() or well that you cannot instantiate and object with new at all. This sometimes happens because the coder provided a no-arg private constructor. This is done when for instance you want the user to instantiate the object using a factory method (that you provide in that class) etc. But still doesn't change the fact that the constructor has to be there (that's part of the language spec).
If you want to know more about the default constructor you can consult the java language spec.
If you do not have a constructor there is an implicit constructor that sets all the members to their default value, e.g. 0 for int
The difference between a constructor and a method is the constructor creates and initializes an object while a method is for an object that already exists. You can think of a constructor as a function that is being called on your newly created object to initialize the data in some way.
JLS takes a special care of a class without constructor:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.
This means that if you don't write any constructor for your class, one will be provided for you by the compiler and all class members will be initialized to default values by Java Virtual Machine.
But once you write a constructor, only that one will be used to create a class instance.
This behavior is usually good for a class that serves as a data structure, while normal class will have some constructor defined with default initialization code.
The answer to your question is, if you do not provide a constructor to a class the JVM will implicitly call the default constructor which has no parameter.
For detailed information about constructor you can refer below link
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Even if you do not explicitly create a constructor in the class, a default constructor will be created during compile time and used.
https://msdn.microsoft.com/en-us/library/aa645608(v=vs.71).aspx
import java.util.*;
public Class C
{
final Vector v;
C()
{
v=new Vector();
}
C(int i)
{
//Here, it is an error. v might not have been initialized.
}
public void someMethod()
{
System.out.println(v.isEmpty());
}
public static void main(String[] args)
{
C c=new C();
c.someMethod();
}
}
The Above code is a compile time error. I know but it says( in NetBeans) variable v should be initialized. When I initialized it in the overloaded constructor it fixes the problem and prints "true". My problem is why should I initialize it again in the overloaded version of constructors.(I have initialized it once in the default constructor ) and I'm not even using the overloaded version. Why?
Because the overloaded constructor does not invoke the default one.
Use this() to invoke it.
When you create a new object, only one of the constructors of your class is called to initialize the object. You seem to think that all of the constructors are called, or that the default (no-arguments) constructor is always called. That is not the case.
So, each constructor needs to initialize all the final member variables.
Note that from one constructor you can explicitly call another one using this(...). For example, as the first line of your C(int i) constructor, you could add a line: this(); to call the C() constructor. Another solution is to initialize the member variable at the line where you declare it:
public class C {
// v will be initialized, no matter which constructor will be used
final Vector v = new Vector();
C() {
}
C(int i) {
// ...
}
// ... etc.
}
Note that you don't need to explicitly initialize non-final member variables; if you don't initialize those, Java will initialize them with a default value (which is null for non-primitive type variables). However, you do need to explicitly initialize final member variables.
Another note: Vector is a legacy collection class. You should prefer using ArrayList instead.
Third note: Use generics to make your code more type-safe. For example, if you need to store strings in a list, use ArrayList<String> instead of the raw type ArrayList.
Overloaded constructor does not call the other version unless you explicitly do it with
this();
That's probably what you want to do.