+ 1
Constructor
public class Vehicle { private String color; Vehicle(){ color="red"; } } Instead of using constructor can't we write it like this : private String color="red"; ?
5 ответов
+ 1
Class used to Creat Objects, you specify value in the Main Par exemple
public class Vehicule{
private int num;
Vehicule(int num){
this.num=num;
}
//As private u need get Set Method
public int getnum(){
return num; //to get value
}
public void setnum(int num){
this.num=num;
}
//method to print
public void Display(){
System.out.println("Num:"+num);
}
}
public class Test{
public static void main (String[]args){
//Creating instance here u set vslue
Vehicule V1 = new Vehicule(1);
Vehivule V2= new Vehicule(5);
V1.setnum(6);
V1.Display();
}
}
+ 1
A private var just availble in class so you need get set method to get or set the value
+ 1
Got it. Thanks :)
0
Is it Java? I mean yu should specify programming language in Tags. 😊
0
You mean to say that it is mandatory to use constructors and get set method when we declare objects as private and can't just use assignment operator to initialize its value?