Lecture 6 Java Objects and Classes
Lecture 6 Java Objects and Classes
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables and
methods from the class.
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
Create a Class
To create a class, use the keyword class:
Main.java
Create a class named "Main" with a variable x:
int x = 5;
Remember that a class should always start with an uppercase first letter, and
that the name of the java file should match the class name.
Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object
name, and use the keyword new:
Example
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
Try it Yourself »
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
int x = 5;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
Try it Yourself »
Using Multiple Classes
You can also create an object of a class and access it in another class. This is
often used for better organization of classes (one class has all the attributes and
methods, while the other class holds the main() method (code to be executed)).
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:
Main.java
Second.java
Main.java
public class Main {
int x = 5;
Second.java
class Second {
System.out.println(myObj.x);
Try it Yourself »
Example
Create a class called "Main" with two attributes: x and y:
int x = 5;
int y = 3;
Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):
The following example will create an object of the Main class, with the
name myObj. We use the x attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
Try it Yourself »
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
int x;
myObj.x = 40;
System.out.println(myObj.x);
Try it Yourself »
int x = 10;
System.out.println(myObj.x);
Try it Yourself »
If you don't want the ability to override existing values, declare the attribute
as final:
Example
public class Main {
System.out.println(myObj.x);
}
}
Try it Yourself »
The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).
Multiple Objects
If you create multiple objects of one class, you can change the attribute values
in one object, without affecting the attribute values in the other:
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
int x = 5;
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
Try it Yourself »
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main {
Try it Yourself »
Example
Create a method named myMethod() in Main:
myMethod() prints a text (the action), when it is called. To call a method, write
the method's name followed by two parentheses () and a semicolon;
Example
Inside main, call myMethod():
System.out.println("Hello World!");
myMethod();
Try it Yourself »
Example
An example to demonstrate the differences
between static and public methods:
// Static method
// Public method
// Main method
}
}
Try it Yourself »
Try it Yourself »
Example explained
1) We created a custom Main class with the class keyword.
3) The fullThrottle() method and the speed() method will print out some text,
when they are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this
in 8).
5) In order to use the Main class and its methods, we need to create
an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and
run the program using the name of the object (myCar), followed by a dot (.),
followed by the name of the method (fullThrottle(); and speed(200);). Notice
that we add an int parameter of 200 inside the speed() method.
Remember that..
The dot (.) is used to access the object's attributes and methods.
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:
Main.java
Second.java
Main.java
public class Main {
Second.java
class Second {
}
}
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:
Example
Create a constructor:
public Main() {
// Outputs 5
Try it Yourself »
Note that the constructor name must match the class name, and it cannot
have a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a
parameter to the constructor (5), which will set the value of x to 5:
Example
public class Main {
int x;
public Main(int y) {
x = y;
}
System.out.println(myObj.x);
// Outputs 5
Try it Yourself »
Example
public class Main {
int modelYear;
String modelName;
modelYear = year;
modelName = name;
Try it Yourself »
Modifiers
By now, you are quite familiar with the public keyword that appears in almost
all of our examples:
The public keyword is an access modifier, meaning that it is used to set the
access level for classes, attributes, methods and constructors.
Access Modifiers
For classes, you can use either public or default:
For attributes, methods and constructors, you can use the one of the
following:
private The code is only accessible within the declared class Try it
»
default The code is only accessible in the same package. This is used when Try it
you don't specify a modifier. You will learn more about packages in »
the Packages chapter
protected The code is accessible in the same package and subclasses. You will Try it
learn more about subclasses and superclasses in the Inheritance »
chapter
Non-Access Modifiers
For classes, you can use either final or abstract:
Modifier Description Try
it
final The class cannot be inherited by other classes (You will learn more Try
about inheritance in the Inheritance chapter) it »
abstract The class cannot be used to create objects (To access an abstract class, Try
it must be inherited from another class. You will learn more about it »
inheritance and abstraction in the Inheritance and Abstraction chapters)
For attributes and methods, you can use the one of the following:
Modifier Description
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods.
The method does not have a body, for example abstract void run();. The
body is provided by the subclass (inherited from). You will learn more
about inheritance and abstraction in
the Inheritance and Abstraction chapters
transient Attributes and methods are skipped when serializing the object containing
them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read
from the "main memory"
Final
If you don't want the ability to override existing attribute values, declare
attributes as final:
Example
public class Main {
System.out.println(myObj.x);
Try it Yourself »
Static
A static method means that it can be accessed without creating an object of
the class, unlike public:
Example
An example to demonstrate the differences
between static and public methods:
// Static method
// Public method
// Main method
Try it Yourself »
Abstract
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass:
Example
// Code from filename: Main.java
// abstract class
abstract class Main {
}
}
class Second {
Try it Yourself »