190 likes | 315 Views
Day 7. Public vs. private instance variables Methods calling methods And type casting. Method Heading. public void writeOutput () { System.out.println (“Name =“ + name): }. Method Heading. Body of Method Definition. Methods calling methods. Warm-up Scenario. UML Class Diagram:.
E N D
Day 7 Public vs. private instance variablesMethods calling methods And type casting
Method Heading public void writeOutput(){ System.out.println(“Name =“ + name): } Method Heading Body of Method Definition
Warm-up Scenario • UML Class Diagram:
public vs. private instance variables • Write a class with public instance variables • Write a main program/file and change the values of the variables on different lines • Can you easily change the values of the variables? Whenever you want?
public vs. private instance variables • Now modify your class so that it has private instance variables • In the main program/file, try to modify the variables on different lines • Can you easily change the values of the variables? Whenever you want?
public vs. private instance variables • In your class, create get and set methods so we can return the values or access them
Revise with private variables • UML Class Diagram:
public vs. private instance variables • Observation: once it’s private, you can’t simply change the value of an instance variable directly. • You can only change it or access it upon calling methods in the class so that everything is encapsulated(actions can only take place by using the class’s methods)
public vs. private instance variables • This way, if you’re sharing a class (i.e., 10 game developers are using one class), the methods are being called upon to update, set or return values.
Type casting • Type cast involves changing the type of a value from its normal type to some other type
Type casting • Type cast involves changing the type of a value from its normal type to some other type • Example: changing a 2.0 to a 2
Type casting • Type cast involves changing the type of a value from its normal type to some other type • Example: changing a 2.0 to a 2 • double distance distance = 9.0;int points; points = distance;
Type casting • Type cast involves changing the type of a value from its normal type to some other type • Example: changing a 2.0 to a 2 • double distance distance = 9.0;int points; points = distance; An illegal assignment
Type casting • Type cast involves changing the type of a value from its normal type to some other type • Using it correctly: • double distance distance = 9.0;int points; points = (int)distance; A legal assignment