Java OOP: Classes, Objects, and Methods
Java OOP: Classes, Objects, and Methods
Java OOP
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:
OOP WITH JAVA
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.
OOP WITH JAVA
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:
int x = 5;
Remember from the Java Syntax chapter 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
OOP WITH JAVA
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;
[Link](myObj.x);
ADVERTISEMENT
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
OOP WITH JAVA
int x = 5;
[Link](myObj1.x);
[Link](myObj2.x);
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:
• [Link]
• [Link]
[Link]
int x = 5;
OOP WITH JAVA
[Link]
class Second {
[Link](myObj.x);
You will learn much more about classes and objects in the next chapters.
OOP WITH JAVA
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:
OOP WITH JAVA
int x = 5;
[Link](myObj.x);
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
int x;
myObj.x = 40;
[Link](myObj.x);
}
OOP WITH JAVA
Example
Change the value of x to 25:
int x = 10;
[Link](myObj.x);
If you don't want the ability to override existing values, declare the attribute as final:
Example
public class Main {
[Link](myObj.x);
The final keyword is useful when you want a variable to always store the same value,
like PI (3.14159...).
The final keyword is called a "modifier". You will learn more about these in the Java
Modifiers Chapter.
ADVERTISEMENT
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;
[Link](myObj1.x); // Outputs 5
OOP WITH JAVA
[Link](myObj2.x); // Outputs 25
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main {
The next chapter will teach you how to create class methods and how to access them
with objects.
OOP WITH JAVA
[Link]("Hello World!");
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():
[Link]("Hello World!");
}
OOP WITH JAVA
myMethod();
In the example above, we created a static method, which means that it can be accessed
without creating an object of the class, unlike public, which can only be accessed by
objects:
Example
An example to demonstrate the differences between static and public methods:
// Static method
// Public method
OOP WITH JAVA
// Main method
Note: You will learn more about these keywords (called modifiers) in the Java
Modifiers chapter.
Example explained
1) We created a custom Main class with the class keyword.
OOP WITH JAVA
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.
To call a method in Java, write the method name followed by a set of parentheses (),
followed by a semicolon (;).
ADVERTISEMENT
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:
• [Link]
• [Link]
[Link]
[Link]
class Second {
Java Constructors
Java Constructors
A constructor in Java is a special method that is used to initialize objects.
public Main() {
}
OOP WITH JAVA
// Outputs 5
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.
ADVERTISEMENT
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;
OOP WITH JAVA
[Link](myObj.x);
// Outputs 5
Example
public class Main {
int modelYear;
String modelName;
modelYear = year;
modelName = name;
Java this
The this keyword is often used to avoid confusion when class attributes have the same
name as method or constructor parameters.
To refer to the class variable and not the parameter, you can use the this keyword:
public Main(int x) {
Output:
Value of x = 5
Tip: Think of this.x = x; as: "this.x (the class variable) gets the value of x (the
parameter)."
Without this, the code above x = x; would set the parameter x equal to itself, and the
class variable would stay uninitialized (0).
This is useful when you want to provide default values or reuse initialization code
instead of repeating it.
Example
public class Main {
int modelYear;
String modelName;
this(2020, modelName);
[Link] = modelYear;
[Link] = modelName;
[Link]();
[Link]();
Output:
2020 Corvette
1969 Mustang
Note: The call to this() must be the first statement inside the constructor.
Java Modifiers
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:
Modifier Description
This is used when you don't specify a modifier. You will learn more about packages
For attributes, methods and constructors, you can use the one of the following:
Modifier Description
Example explained
Here, name is declared as public, so it can be accessed from outside the Person class.
But age is declared as private, so it can only be used inside the Person class.
OOP WITH JAVA
Non-Access Modifiers
Non-access modifiers do not control visibility (like public or private), but instead
add other features to classes, methods, and attributes.
The most commonly used non-access modifiers are final, static, and abstract.
Final
If you don't want the ability to override existing attribute values, declare attributes
as final:
[Link](myObj.x);
OOP WITH JAVA
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
OOP WITH JAVA
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: [Link]
// abstract class
abstract class Main {
class Second {
}
OOP WITH JAVA
Modifier Description
final The class cannot be inherited by other classes (You will learn more about inheritance
abstract The class cannot be used to create objects (To access an abstract class, it must be inh
about 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
body is provided by the subclass (inherited from). You will learn more about inheritan
transient Attributes and methods are skipped when serializing the object containing them
OOP WITH JAVA
volatile The value of an attribute is not cached thread-locally, and is always read from the "ma
OOP WITH JAVA
Java Encapsulation
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from
users. To achieve this, you must:
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case:
// Getter
return name;
OOP WITH JAVA
// Setter
[Link] = newName;
Example explained
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside
this class:
Example
public class Main {
[Link]([Link]); // error
If the variable was declared as public, we would expect the following output:
OOP WITH JAVA
John
Instead, we use the getName() and setName() methods to access and update the variable:
Example
public class Main {
[Link]([Link]());
// Outputs "John"
Why Encapsulation?
• Better control of class attributes and methods
OOP WITH JAVA
• Class attributes can be made read-only (if you only use the get method),
or write-only (if you only use the set method)
• Flexible: the programmer can change one part of the code without affecting
other parts
• Increased security of data
OOP WITH JAVA
Java Packages
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much
much more. The complete list can be found at Oracles
website: [Link]
The library is divided into packages and classes. Meaning you can either import a single
class (along with its methods and attributes), or a whole package that contain all the
classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get
user input, write the following code:
Example
import [Link];
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
import [Link];
class Main {
[Link]("Enter username");
}
OOP WITH JAVA
ADVERTISEMENT
Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the [Link] package. This package also contains date and time
facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the [Link] package:
Example
import [Link].*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:
Example
└── root
└── mypack
└── [Link]
[Link]
package mypack;
class MyPackageClass {
[Link]("This is my package!");
The -d keyword specifies the destination for where to save the class file. You can use any
directory name, like c:/user (windows), or, if you want to keep the package within the
same directory, you can use the dot sign ".", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class
names.
When we compiled the package in the example above, a new folder was created, called
"mypack".
This is my package!
OOP WITH JAVA
Java Inheritance
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):
[Link]("Tuut, tuut!");
// Call the honk() method (from the Vehicle class) on the myCar
object
[Link]();
We set the brand attribute in Vehicle to a protected access modifier. If it was set
to private, the Car class would not be able to access it.
- It is useful for code reusability: reuse attributes and methods of an existing class when
you create a new class.
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods
to perform different tasks.
ADVERTISEMENT
...
...
Java Polymorphism
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and
methods from another class. Polymorphism uses those methods to perform different
tasks. This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
}
OOP WITH JAVA
Remember from the Inheritance chapter that we use the extends keyword to inherit from
a class.
Now we can create Pig and Dog objects and call the animalSound() method on both of
them:
Example
class Animal {
class Main {
[Link]();
[Link]();
[Link]();
- It is useful for code reusability: reuse attributes and methods of an existing class when
you create a new class.
OOP WITH JAVA
Java super
The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
[Link]();
Output:
The animal makes a sound
The dog says: bow wow
Note: Use super when you want to call a method from the parent class that has been
overridden in the child class.
Example
class Animal {
[Link]();
Output:
Animal
Example
class Animal {
Animal() {
[Link]("Animal is created");
Dog() {
[Link]("Dog is created");
Output:
Animal is created
Dog is created
Note: The call to super() must be the first statement in the subclass constructor.
OOP WITH JAVA
To access the inner class, create an object of the outer class, and then create an object
of the inner class:
int x = 10;
class InnerClass {
int y = 5;
[Link](myInner.y + myOuter.x);
}
OOP WITH JAVA
// Outputs 15 (5 + 10)
Example
class OuterClass {
int x = 10;
int y = 5;
[Link](myInner.y + myOuter.x);
}
OOP WITH JAVA
If you try to access a private inner class from an outside class, an error occurs:
[Link]: error: [Link] has private access in OuterClass
[Link] myInner = [Link] InnerClass();
^
ADVERTISEMENT
Example
class OuterClass {
int x = 10;
int y = 5;
[Link](myInner.y);
// Outputs 5
Note: just like static attributes and methods, a static inner class does not have access
to members of the outer class.
Example
class OuterClass {
int x = 10;
class InnerClass {
return x;
[Link]([Link]());
// Outputs 10
OOP WITH JAVA
Java Abstraction
The abstract keyword is a non-access modifier, used for classes and methods:
• Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
• Abstract method: can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).
[Link]("Zzz");
From the example above, it is not possible to create an object of the Animal class:
OOP WITH JAVA
To access the abstract class, it must be inherited from another class. Let's convert the
Animal class we used in the Polymorphism chapter to an abstract class:
Remember from the Inheritance chapter that we use the extends keyword to inherit from
a class.
// Regular method
[Link]("Zzz");
class Main {
OOP WITH JAVA
[Link]();
[Link]();
To achieve security - hide certain details and only show the important details of an
object.
Note: Abstraction can also be achieved with Interfaces, which you will learn more about
in the next chapter.
OOP WITH JAVA