d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Question About Methods
Add Reply New Topic New Poll
Member
Posts: 31,292
Joined: Mar 25 2009
Gold: 0.00
Oct 22 2017 12:55am
Class Car:

Code
package com.company;

public class Car {

private int doors;
private int wheels;
private String model;
private String engine;
private String colour;


public void setModel(String model) {
String validModel = model.toLowerCase();
if(validModel.equals("carrera") || validModel.equals("commodore")) {
this.model = model;
} else {
this.model = "unknown";
}

}

public String getModel() {
return this.model;
}


}


Code

main:

package com.company;

public class Main {

public static void main(String[] args) {
Car porshe = new Car();
Car holden = new Car();
porshe.setModel("carrera");
System.out.println("Model is " + porshe.getModel());
}
}



My question is this, I thought methods couldn't access info from another method? Cuz of encapsulation?
but in these methods it does... for example:

this.model = model;
} else {
this.model = "unknown";
}


^part of method setModel



yet the method getModel, accesses model from getModel....:

public String getModel() {
return this.model;
Member
Posts: 1,039
Joined: Jul 8 2008
Gold: 1,939.50
Oct 22 2017 11:26am
You can access private instance variables within the class. See https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

If you want to specify a variable you can only access in a particular method then you need to declare it in that method.

This post was edited by waraholic on Oct 22 2017 11:27am
Member
Posts: 31,292
Joined: Mar 25 2009
Gold: 0.00
Oct 22 2017 11:35am
Quote (waraholic @ Oct 22 2017 01:26pm)
You can access private instance variables within the class. See https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

If you want to specify a variable you can only access in a particular method then you need to declare it in that method.


gotchya thanks
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll