Classes in Java
Classes
• All code in a Java program is part of a class
• A class has two purposes
– Provide functions to do work for the programmer
– Represent data
• Two kinds of things found in a class
– Variables store data about the class
– Methods provide programmers with ways of asking the
class to do work
Defining a Class
1. Starts with class myClass {
the word “class” ...
... 2. Followed 3. Followed
by the class by an open
... name curly bracket
4. Followed by }
method and
variable
What name
definitions.
5. Followed by a close would this
curly bracket file have?
Indenting Classes
• Variables and methods in a class myClass{
class should be indented void method1(){
• Close bracket at end should
be indented the same as code
class }
• Open bracket can be on same }
line as class or next line
• Classes are usually in their
own file
Formatting Java Programs
• Java is case sensitive. E.g. class myclass is not the same
as class MyClass.
• Java is white space insensitive
– Can put any number of spaces or new line characters between
statements
– Should use spaces to indent to make programs readable
• // (two slashes) in Java start a comment:
// This is a comment
– Everything from the // to the end of line is ignored
Summary
• Java programs are made up of classes
– Classes have variables that store data
– Methods do work for the programmer
• Class definitions have multiple parts.
• Java is case sensitive
• Comments and extra white space are ignored