0

Can anybody tell me about java class by easiest way. Like you are teaching to a small boy child?

I am having a lots of difficulty studying classes in Java please any body explain me.

5th Nov 2016, 10:31 AM
nayan
nayan - avatar
1 ответ
+ 3
A class is no more than a definition of an object. Say you want to define a car, you would need to create a class like that : public class Car { } But your car is nothing without things to define it, for instance a color or a max speed. That's why you need to add what are called parameters. In that example, I will add a color of type String and a maxSpeed of type int : public String color; public int maxSpeed; But I also want to be able to create a new car, without which my class would be useless. For that, I create a constructor, like that : public Car(String color, int maxSpeed) { this.color = color; this.maxSpeed = maxSpeed; } Here, you can see that the constructor is a special function, and I use the keyword "this", which is used to talk about the variable used by the class instead of the one used in the parameter of the constructor. Now, if you want to create a new object of type Car, you can do it this way : Car myCar = new Car("red", 150); And you can access the different elements of your car using this syntax : // Prints: red System.out.println(myCar.color); In the end, your class looks like that : public class Car { public String color ; public int maxSpeed; public Car(String color, int maxSpeed) { this.color = color; this.maxSpeed = maxSpeed; } } Of course, these are only the very basics of creating a class, and setting public parameters is not a good practice (you should set them to private and use getters/setters), but I hope it helped you understand. You can find more details in the Java course.
5th Nov 2016, 11:05 AM
Pierre Varlez
Pierre Varlez - avatar