Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi all,

I'm new to java and i'm trying to figure out if we could assign values to variables when declaring a function.

Here is some explanation (Correct me if i'm wrong)

in C++ We could write:
C#
class Humain 
{
public:
    String nom;
    int age;
public:
    Humain(int age, String name): age(age), name(name){}
}


I'm wondering if we could write in java like that.

PS: i looked in many web sites and all used as below

Java
Humain(int age, String name){
   this.age = age;
   this. name = name;
}


Thank you.
Posted
Updated 26-Apr-12 0:39am
v2
Comments
enhzflep 26-Apr-12 6:29am    
I'm almost certain I'm being unnecessarily pedantic - but since 1 misplaced character in MBs of source code can kill a program, I thought it pertinent to mention that the c++ class definition should read: (Sorry, not sure of the equivalent in Java)

class Humain
{
public:
Humain(int age, string name): age(age), nom(name){}
private:
string nom;
int age;
};
Schehaider_Aymen 26-Apr-12 6:38am    
yeah you saif right but i pasted the code from a java test prog that i wrote so i missed the public: and all went private in my example :) but still not the subject here.

Thank you for the remarque


V2: Updated
Richard MacCutchan 26-Apr-12 6:54am    
I don't think that syntax exists in Java; what happens when you try it?
Schehaider_Aymen 26-Apr-12 7:13am    
it gives several errors beginning with :

I have to implement the function age ... so i thought that may be it exists but i wrote it wrong
Richard MacCutchan 26-Apr-12 7:38am    
beginning with ... ?

1 solution

Unlike C++ you can specify initial values in your class but you can't use an initialiser list. Quite what that does for performance I don't know but I assume the compiler removes redundant initialisation.

Cheers,

Ash

PS: Have you got a copy of "The Java Programming Language" by Arnold, Gosling and Holmes? If not grab a copy, it's got answers like this in it. (That's where I got the answer to this question BTW).
 
Share this answer
 
v2
Comments
Schehaider_Aymen 26-Apr-12 10:16am    
Could you tell me the section number from wich you got the answer?

Thank you.
Espen Harlinn 26-Apr-12 10:36am    
N3242 - 12.6.1-8
Espen Harlinn 26-Apr-12 10:34am    
Have a 5 even if this is now valid C++:

struct C {
C() { } // initializes members as follows:
int i; // OK: i has indeterminate value
int j = 5; // OK: j has the value 5
};

/* C++11 feature */
Aescleal 26-Apr-12 20:18pm    
cool, I'll have to have a play with that!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900