+ 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"; ?

2nd Jan 2018, 4:49 AM
Shalini Jha
Shalini Jha - avatar
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(); } }
2nd Jan 2018, 4:58 AM
Elie Douaihy
Elie Douaihy - avatar
+ 1
A private var just availble in class so you need get set method to get or set the value
2nd Jan 2018, 5:03 AM
Elie Douaihy
Elie Douaihy - avatar
+ 1
Got it. Thanks :)
2nd Jan 2018, 5:05 AM
Shalini Jha
Shalini Jha - avatar
0
Is it Java? I mean yu should specify programming language in Tags. 😊
2nd Jan 2018, 4:50 AM
Uttam
Uttam - avatar
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?
2nd Jan 2018, 5:01 AM
Shalini Jha
Shalini Jha - avatar