the few things that i cant understand are inside the code..


The code should give out the car type, model type ,serial number. and the number of cars..

public class part5{

	public static void main(String[] args) {
		System.out.println(Car.getCounter());
		Car[] cars =new Car[5];
		for (int i = 0; i < cars.length; i++) {
			cars[i]=new Car("Audi A"+(i+1), ""+(2000+i));
		}
		
		for (Car car : cars) {
			System.out.println(car); // where does it go? and what does it print when it reaches there? whats the difference between , each for loop and a normal loop?
		}
		System.out.println(Car.getCounter());
		cars=null;
		System.out.println(Car.getCounter());// why to put this statement again after the variable cars was defined to be null?
	}
	
	
}

class Car{
	
	String name;
	String model;
	private static int counter;
	int serialNumber;
	public Car(String name, String model) { // why is the Car method has public before it? why the method has a capital letter ?
		this.name = name;
		this.model = model;
		counter++;
		serialNumber=counter; // why serial number doesnt have  "this." before it?
	}
	
	public String toString() {
		return "Car [name=" + name + ", model=" + model + ", serialNumber="
				+ serialNumber + "]"; // when this is returned, where does that long string go to?
	}
	public static int getCounter(){
		return counter;
	}
	
	
}

Recommended Answers

All 14 Replies

You can find the answers to many of these questions if you use Google and a bit of intelligent work. But here's the answer to two that are not so easy to find...
System.out is the Java console, which is the window where you ran the program if you're using a command prompt.. Its println(...) method prints things to that destination. When it prints things, it calls their toString() method to get a printable version of them. That's why the Car class has a toString method.
So line 11 implicitly calls line 34 to get a printable String version of the car, and prints that to the java console.

class Car{
 
String name;
String model;
private static int counter;
int serialNumber;
public Car(String name, String model) { // why is the Car method has public before it? why the method has a capital letter ?
this.name = name;
this.model = model;
counter++;
serialNumber=counter; // why serial number doesnt have "this." before it?
}

public Car(String name, String model) this is constructor of the Car class. read about constructors here http://math.hws.edu/javanotes/c5/s2.html
why it's public, it means you can have access for creating car object outside this class and even package. You should check for different visibility modifiers (public, private, protected), google for visibility java

this.name refers to the class's variable name. The red ones are referring to same variables and just like the green ones.
you can read here for example about this. http://math.hws.edu/javanotes/c5/s6.html or google for this java

System.out.println(Car.getCounter());// why to put this statement again after the variable cars was defined to be null?

The variable cars points to an array of objects, each member of that array is an object of type Car. That array might contain, for example, Ram's Tata Nano and Guiseppe's Fiat and my Dodge Dart and Hiro's Toyota and Jurgen's Volvo - these are particular cars. When you declare that array, cars, to be null, you eliminate those references to those Car objects. There may be other references elsewhere in the program, in which case these Cars will continue to exist. In the program as you've given it, there are no other references, so these Cars will cease to exist and their memory will be recovered by the Garbage Collector.

Now, how does this affect the call to Car.getCounter()? Actually, as you'll see if you run the program, it doesn't. Car has a static field called counter which is incremented each time a car is created, but it makes no effort to track how many cars still exist. So if I've created five Cars, counter will be five. If I send three of those Cars to the garbage collector, counter will still be five. If I then create three more, there will be five cars total on the heap, but counter will read eight.

So you can see that despite the similarity of the names, setting the array cars[] to null does not affect the static field Car.counter, which you read by calling Car.getCounter. This means that counter is actually not a counter at all, it's more like a serial number. It puts a unique integer on each instance of Car that is created, but you can't call it to find out how many Cars currently exist.

There is a piece of code in there, which is known as --> Enhanced Java for Loop

for (Car car : cars)

What it's saying is that, define a new Car instance, called car, which goes through the items of array cars. It will INTELLIGENTLY stop as soon as hits the end of array. Very efficient to use, although it looks a little bizarre at first.

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

Take a look at the above link, it's discussed in details.

i didnt know you can put a constructor just inside the object

public Car(String name, String model)

it is writen as a method.

is it the same as if i wrote

Car mazda=new Car(String name, String model);

A constructor is a special method that you define inside the class.
It's called when hyou create a new instance of that class.
So

public Car(String name, String model) {...}

defines the constructor method and

Car mazda=new Car("MAzda", "something");

calls that method to create a new Car.

Car mazda=new Car(String name, String model);

is wrong.

why is it wrong, why cant i call for a constructor method while the variables inside ?

You use the syntax
Car(String name, String model)
to define the method, and you use syntax like
Car("Mazda", "something")
or even
String a = "Mazda", b = "etc"; new Car(a,b);
to call the method
the new keyword is used when calling a constructor, so it's the second version.
It's just how Java syntax works.

It actually is a good question. I was just looking at my ceiling and I found out a rather good example for you.

Alright; imagine that you want to buy a chandelier. You see the chandelier in the shop you purchase it and it's still in a box. You can't use it yet, although it's there but you can't use it. You need to wire it up to electricity and then use any kind of lamp (as long as it's the compatible type) and there you have your light.

Same goes for constructor, a constructor definition, is a chandelier in a box, although you have the parameters, first you have to plug it. Plugging occurs through creating an instance, and using the proper lamp is equivalent to using the proper data type, say string. You can use anything for your parameter as long as it's the proper type (string --> type of lamp, "Mazad" --> 100W lamp).

I hope I could make it clear.

thanks group, it did make it clear.

so that car method is being used as an object that contains variables.

is it the same as if i wrote at the main.

Car car=new Car();

and the method in the car class
void init(String model, String type){
this.model=model;
this.type=type;
}

and then if i called the method like this .. Car.init(mazda, auto)

is it the same?


another question, what if i dont put public before the Car.

i would live it Car("Mazda", "something")
without the public. what would happen? what would it mean?

and then if i called the method like this .. Car.init(mazda, auto)

No, I don't see any way that that would work. In order to call it as "Car.init(mazda, auto)", you'd have to have init() declared as a static method. Static methods have no "this" - that's part of being static - so the method wouldn't compile if it were static.

You could do something like this, this might be sort of what you're talking about:

(Assume Car has a no-arg constructor, and an init method as above.)
(this is pseudo-code, obviously)

Car tempCar = new Car();

  // somewhere in here we acquire the parameters - make, model, etc)

  tempCar.init(parameters);

What's happening here is, you're declaring a new Car object - something might be happening in the constructor, but it's nothing we know about. Might be assigning a serial number to the car, or what have you. In the course of the following code, we learn what the make and model of the car is, so we can set that.
Perhaps this would be in a PrivateInvestigator object - the Investigator has discovered that there's a car involved in the case, but he doesn't know anything more about the car than that it exists. So he creates a Car, with no characteristics. As he finds out more about the car, he stores the information, but he needs to start by creating a blank car.
Or you might have a similar case in a Second-Life type game, or a Car Wars auto generator (anybody remember Car Wars? :) ). A character decides they want a customized "car" - it starts off as a generic, and as they tweak it, characteristics are assigned. Or, you might use something like this in a tool for submitting a classified ad.
Really, any application that required a placeholder object of this sort could take this form. It would more likely consist of a set of setter methods than something called "init" but the effect would be the same.

The thing that the constructor must do is to allocate memory and return a reference to that memory. Everything else - setting default values or parameterized values for fields, updating static counters or serial number generators, setting off alarms in other parts of the program ("Warning! Unauthorized creation of Car!"), or anything else you can think of - everything else is secondary, as long as the memory is allocated.

another question, what if i dont put public before the Car.

i would live it Car("Mazda", "something")
without the public. what would happen? what would it mean?

I'd have to check the JLS, but I assume your constructor would have package access. This would mean that only classes in the same package could create Cars.
(see JLS 6.6.5)

is it the same as if i wrote at the main.

Car car=new Car();

and the method in the car class
void init(String model, String type){
this.model=model;
this.type=type;
}

and then if i called the method like this .. Car.init(mazda, auto)

is it the same?

Almost - you have a mistake in Car.init(mazda, auto). Car is the class. This should read car.init(mazda, auto) car (lower=case c) is the individual Car object that you are trying to initialise.

As for "public" - this controls who is allowed to access this method, inj this case, anybody. Without public, only methods defined in the same package can call it (that was oversimplified to make a point). You can google for the details.

i get it guys , you made it clear for me. i think things start to get clear for me..

i have a few java books that i am reading now.

damn i spend so much time understanding java. looks simple but it is complex..

thread solved!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.