Anatomy of a class Oliver W. Layton CS231: Data Structures and Algorithms Lecture 02, Fall 2018 Friday September 7
Follow-up Python is also cross-platform. What s the advantage of Java? It s true: Python does run flexibly on all OSes that support Python. Bytecode compilation optimizes your source code and does all the checking for syntax errors/figuring out variable types/validity/etc. The JVM converts the bytecode to instructions that the computer actually can execute. Remember, Python has to do all this, plus execute your code when you run the interpreter. This means Java code can be faster than Python code (but not always). double vs. float (draw on board)
Quick review: What are the big differences between Java and Python? 1. Java is compiled, Python is interpreted. 2. Java requires a 'main method'. 3. Java is a statically typed language, Python is dynamically typed. 4. Java is an object-oriented language.
Quick review: What are the big differences between Java and Python? Java Java example Python Python example compiled javac Main.java -> java Main interpreted python main.py Needs main method. Is executed when program runs. public static void main(string[] args) Not required. Top-level code just runs. closest thing: def main(): or if name == ' main ': Statically typed int x = 3; Dynamically typed x = 3 Object-oriented Code is generally enclosed in a class. Supports OO
Anatomy of a Java class Dive into example: Die.java
Instance variables Instance variables go inside the class definition, usually at the very top. Instance variables and methods are called fields and belong to a class.
Naming Quick word about naming: Java classes should be title case, like we discussed last time (e.g. HelloWorld). Variables should be camel case (e.g. facevalue ). Underscores are supported.
Inline comments Unlike Python, which uses the # symbol for single line comments, Java uses two forward slashes for single-line (inline) comments: // current face value private int facevalue;
Multiline comments 1/2 Unlike Python, which uses the triple quote ''' for multiline comments, Java uses /**/ (// with two *s in between), with the * symbol at the beginning of each line: /** * Die.java * Represents a 6-sided die * Oliver W. Layton * CS231: Data structures and algorithms, Fall 2018 * Project XX: YY name */ public class Die { // current face value private int facevalue;... // more code } // end of Die class
Multiline comments 2/2 When you turn in your projects, please add comment the top of each.java file to include: Filename Description of the class Your name Our class name Which project you're turning in. Use the multi-line style comments above each method signature to give a brief description what it does.
final keyword In Java, we can use the final keyword to indicate to the Java compiler that a variable should never change. final variables MUST be initialized at declaration. If someone tries to change the value, Java will not allow us to compile the program. A naming convention for constants is that they are all caps, words separated by underscores. You don't need to follow this, but it helps to visually remember that the variable is a constant.
Access modifiers: public Who can access fields in a class? Examples below refer to the Student/Teacher/Undergraduate/Graduate drawing from class public means anyone can access the field, the field is exposed to the world. Example usage: public int grade; in the class Student. Syntax for access is: ClassObject.field. For example: mike.grade, where mike is an object of type Student and grade is an instance variable in the class Student. Whether you created a subclass, a separate independent class, or I created totally separate program and found your.class files, I could access your field data if it's public
Access modifiers: private Example usage: private int grade; The private keyword is generally the preferred choice for ALL class fields because that means nothing outside the class to which the field belongs can access the data. WE control the access via set/get methods. Not even subclasses can access private fields.
Access modifiers: default Example usage: int grade; No explicit modifier; it's omitted. It's like public, but only classes within the same package can access the data. Package: you can think of this for now as other classes within the same working folder on your computer (e.g. in School1 folder). Default is sometimes called package scope for this reason.
Access modifiers: protected Example usage: protected int grade; Same as default access, except subclasses located in different packages can access the data. We're not concerned with the distinction between protected and default in CS231.
void keyword Used when a method has no return value. For example, let's say the following is defined in the class Die: public void setvalue(int newvalue) { // code here... } We may call it as follows: thedie.setvalue(2); where thedie is an object of type Die.
this keyword (1/2) Consider this set method: public class Die { // current face value private int facevalue; } public void setvalue(int facevalue) { this.facevalue = facevalue; } that is called on the object thedie: thedie.setvalue(2);
this keyword (2/2) this refers to the facevalue instance variable belonging to thedie, NOT the parameter value passed in. this is needed in the above example because there is a name conflict between the parameter name and the instance variable. this allows you to differentiate between the two and refer to the instance variable. It's similar to self in Python.
Instantiating an object in memory Here's code to make a new object: public static void main(string[] args) { Die thedie = new Die(); } The new keyword tells Java to allocate memory for a new object instance. This is called instantiation -- we instantiated the Die object.
Default constructor (1/2) The last piece after new (Die()) is a call to what's called the default constructor. Wait!!! We didn't write a constructor! How does it know... Every Java object automatically comes with a parameter-less constructor for any type of object that essentially does nothing except instance variables are set to default values (e.g. 0 for int, 0.0 for double, etc).
Default constructor (2/2) Often, we'll want to customize what happens in the constructor, when a new object is created. For example, set the facevalue to 1 when we create a new Die, rather than the default value of 0. We can do something called override the default constructor --- define a method with exactly the same method signature and then Java will call OUR default constructor, rather than the built-in one: public Die() { facevalue = 1; }