Classes, constructors and methods
Hi, i'm new to programming and chose Java to be the one. I've been studying it from numberous sites but i'm still stuck on some definitions.
For my understanding a Class has, at least, a constructor that creates instances of the class and have no return value, and a method to provide the behaviour of the instance. Is that right?
I'm confused about the syntax of constructors and methods:
Example: Class Dogs{
/**class fields*/
String name;
String owner;
/**constructor*/
public Dogs(String dogName; String dogOwner){
name=dogName;
owner=dogOwner;
}
/**methods.....*/
}
Is it right? The dog can have same names but different owners or have the owner but different names. If not it is the same instance isn't it? My doubt is also in the sintax inside a constructor: nameOfTheClass variable = new nameOfTheClass. Why isn't it used all the times?
Re: Classes, constructors and methods
Re: Classes, constructors and methods
Thanks but i've been reading it and others...
I'm looking for an user's point of view as it seems I cannot really understand the explanations i've seen. I've been reading more in a good book (i think) and learned a little bit more of what an object really is and where it came from. It seems an object is a very well encapsulated structure that is defined by its by its variables and private methods and can communicate (interact) with other objects also on methods. This is my understanding of it. I'm trying to understand it's logic before i can get to constructors although i have an idea of them.
Re: Classes, constructors and methods
Ok listen Class have two things data members(mean variables) and member funtions (mean methods or funtions).... The name of your constructor should be same as the name of your class. e.g
Code:
class Test
{
int a;
float b;
Test()
{
a=0;
b=0.0;
}
}
Now you can use private or public with classes but at the moment leave it...
Constructor have no return type....
Now what are member funtions.....
Funtions that use your data members now if you want to set value of a nd b at run time then there will be two set funtions like
Code:
public void set_a(int x)
{
a=x;
}
public void set_b(float y)
{
b=y;
}
Now what is object?? in main funtion you will have to do Test obj=new Test();
Now in this line Test is you class name and it will be data type of object which means that every object of this classs will have two variable int a and float b..... now when you will create another object it will have its own two same variables... further obj is name of object you can change it..... new means object is being created at heap means at run time ... Test() is your constructor which gives 0 and 0.0 to a nd b respectively....
Hope you understand it.....