Tuesday, 23 January 2024

Accesss Modifiers Java

 Access modifiers in Java are keywords that determine the visibility and accessibility of classes, fields, methods, and other members within a Java program. There are four main access modifiers in Java:

a) Private : Have access within same class

b)Public : No Restriction on Access

c) Protected: Have access within same Package

//Q)Discuss the importance of access modifiers in Java classes.
// Provide an example where using private and public access modifiers makes sense.(Toyota,Camry)
package mypack;

public class Car {
private String model;
public String brand;

public Car(String model, String brand) {
this.model = model;
this.brand = brand;
}

public String getModel() {
return model;
}


}

package mypack;

public class CarOwner {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry");

// Accessing public members directly
System.out.println("Brand: " + myCar.brand);

// Accessing private members through public methods
System.out.println("Model: " + myCar.getModel());

}
}




*******************************

No comments:

Post a Comment

Rest and spread operator in javascript

  Absolutely 👍 — here are several practical and clear examples of the rest operator ( ... ) in JavaScript, covering functions, arrays, an...