Another new face emerges — @phvismin just made waves with 16 #NFTs 🌊🔥 Huge thanks for bringing such strong energy into the NFToa ecosystem. Moves like this push us all forward 🙌 #eCash $XEC #NFTCommunity #NFTCollection #NFTCollectors #nftprimearts #CryptoMarket #CryptoRecovery pic.twitter.com/T9zkiKPDGj
— NFToa (@nftoa_) September 2, 2025
You may have seen the image of a cup with steam rising from it and the word Java like in Figure 8.1. Yes, this is the logo of the Java programming language, which has been gaining popularity in recent years. Many games and applications used on mobile devices such as mobile phones and PDAs are made with this language. This language is known for its portability and support for object-oriented programming concepts.
This chapter covers two competency standards, namely creating programs in object-oriented programming languages and creating application programs using Java. This is because of the closeness of the concepts between Java and object-oriented programming. The competency standard for creating programs in object-oriented programming languages consists of four basic competencies, namely data types and program control, class creation, use of inheritance, polymorphism, and overloading, and use of interfaces and packages. While the competency standard for creating application programs using Java consists of five basic competencies, namely explaining file I/O, data types and variables, implementing operators, explaining exception handling, implementing multithreading and explaining network programming.
In the presentation in this book, one sub-chapter does not directly refer to one basic competency. A summary is placed at the end of each chapter and then continued with practice questions. Before studying this competency, remember the operating system, problem-solving principles, basic and advanced programming algorithms, programming with VB and VB.Net and supporting materials from other subjects.
Objective
After studying this chapter, it is expected that readers will be able to:
- Understanding the concept of object-oriented programming
- Explaining File I/O, data types and variables in Java
- Using operators
- Implementing program controls
- Explaining Exception Handling
- Implementing Multi-Threading
- Explaining Network Programming
- Creating object-oriented programs with classes
- Using the principles of inheritance, polymorphism and overloading
- Creating object-oriented programs with interfaces and packages
1. Object Oriented Programming Concept
Object Oriented Programming (OOP) is a programming paradigm that uses objects and their interactions to design computer programs and applications. OOP was not widely used before the early 1990s. But now it has become something that is commonly used. Programming languages such as the dotNet family from Microsoft (Visual Basic.Net, Visual C#, and Visual J), Borland Delphi, Java, Python, PHP version 5 and above, C++ and many others are programming languages that support the concept of OOP.
What is an object? All objects in this world can be called objects. Your RPL subject teacher is an object. This book you are holding is also an object. Even the RPL subject is also an object. Each object will have certain characteristics and behaviors. Characteristics are called attributes and behaviors are called behaviors or methods.
In the definition of object-oriented programming, there are classes and objects. Class defines the abstract characteristics of something including the attributes or properties of something and what can be done by something (method). For example, a car is a class that has attributes of color, brand, type and others. Cars also have methods including, forward, backward and stop (see Figure 8.2).

Figure 8.2. Classes, attributes and methods.
Objects are examples of classes that have been defined. The attributes and methods of the class will automatically be passed down to the object but with specificity. As an illustration, let's look at Figure 8.2. In the figure, we can identify the class as a car with its attributes and methods. The object is a sedan with the Toyota brand, and its color is red. The sedan also has forward, backward and stop methods. In this case, the sedan is called an instance or derivative of the car class.
There are several important concepts that you must understand in object-oriented programming, namely, abstraction, encapsulation, inheritance and polymorphism.
2. Abstraction
Abstraction or also called composition is a principle of simplification of something complex by modeling the class according to the problem. To further clarify the understanding, try to look at Figure 8.3. In the picture, a car is seen if its parts are broken down we will get things like tires, engines, car frames, glass, and others and vice versa. If we combine these parts, we will get a car class. In object-oriented programming, usually if we encounter several classes or objects that if identified have many similarities in attributes and methods, we will combine these classes into one super class.

Figure 8.3. Example of abstraction.
3. Encapsulation
The principle of encapsulation is the principle of hiding the details of a class from objects that interact with it. For example, when we drive a car, we are actually interacting and we ask the car to run its methods such as moving forward, backward or stopping. We interact only with some parts of the car (interface) such as gears, steering wheel, gas pedal, brake pedal and other parts. But the details of the process that occurs inside the car, how it can move forward, backward or stop, we don't need to know.
4. Inheritance
Inheritance is the principle of inheritance of properties from parents to children or descendants applied to classes. Parents have more general attributes and methods compared to children or descendants. In Figure 8.4. we can see that cars have more general attributes and methods compared to sedans, trucks or buses. Cars as the class that inherits are called super classes, while sedans, trucks and buses as the classes that are inherited are called sub classes.

Figure 8.4. Inheritance.
5. Polymorphism
Polymorphism is probably the most difficult object-oriented programming concept to understand. The meaning of polymorphism is the ability of an object to have more than one form. Or in other words, we can implement something differently through the same method. For example, if there are four different animals, namely birds, snakes, frogs, and lions, then we ask them to move, then the bird will fly, the snake will crawl, the frog will jump, the lion might run. So the same method might be implemented differently if the objects that implement it are different.
6. Introduction to Java
The first Java programming language was born from The Green Project, which ran for 18 months, from early 1991 to the summer of 1992. The project used a version called Oak. The name Oak was not used for the release version of Java because a software was already registered with the trademark, so the replacement name was taken as "Java". This name is taken from pure coffee that is ground directly from the beans (tubruk coffee). Currently Java is under the license of Sun Microsystems.
According to Sun's definition, Java is the name for a set of technologies for creating and running software on standalone computers or in a network environment. People who are involved in the world of programming prefer to call Java a technology rather than just a programming language, because Java is more complete than a conventional programming language.
7. Software Requirements
To create a Java program, at least two pieces of software must be available, namely:
Java 2 SDK Standard Edition (J2SE)
This software is what we will use to compile the Java program code that we create. In addition, this software provides classes that we can use to build desktop applications, graphics, security, database connectivity and networks. This software can be downloaded for free on the Sun Microsystem website. After that, this software must be installed on the operating system that we use.
Text Editor
This software is used to write program codes. Notepad, Vi, Gedit, are examples of text editors that can be used. However, using a text editor is rather difficult because there are no support facilities that make it easier to write program codes. Currently, several IDEs are available for free on the internet. These IDEs have provided many facilities such as syntax coloring, auto completion, and templates to make it easier to create Java-based applications. NetBeans (www.netbeans.org) and Eclipse (www.eclipse.org) are two very well-known and very powerful IDEs. Figure 8.5 shows the NetBeans IDE display.

Figure 8.5. NetBeans IDE.
8. Compile Program Code
Before we create a program and compile it we must set the ClassPath. ClassPath is a variable system used to tell a program written in Java where the locations will be used. For example, we put our program code in the directory d:\TestCode\Java, then we need to set the path so that we can use the Java compiler from this directory. Here are the steps to create a classpath:
Open the command prompt in Windows then once it is open type:
Set PATH=C:\progra~1\java\jdk1.5.0\bin;%PATH%
Set CLASSPATH=.;D:\TestCode\JavaThe path above is if we use JDK version 1.5, if it's another version then just adjust.
Check if the settings are correct by typing the java command in any directory from the command prompt.
After the classpath is created, try opening Notepad then type the following code;
public class Main {
//isi blok
public static void main(String[] args) {
System.out.println("Hallo ini Java lho");
}
}Then save the code file with the same name as the class in the code, namely Main and ending with the extension .java. Save it in the location we have specified above (see Figure 8.6). The rules for writing file names in Java are very strict, so if you give a file name that is not the same as the class name, the program will refuse to execute.
In the program code above, the first line shows the class name, Main. In Java, all code should be placed inside the class declaration. We do this by using the class keyword. In addition, the class uses the special public access, which indicates that our class has free access to other classes from other packages (a package is a collection of classes).
After the class declaration, the { sign is followed, indicating the beginning of the code block. This sign must be closed with a } sign as the end of the block.
The line that starts with // is a comment. Then the next line is the method name declaration. In this case, the method name is main (main method). We can create other methods outside of this main. After this declaration, it is also followed by a code block. The code block contains the statement System.out.println("Hello, this is Java");. The System.out.println() command displays text enclosed in double quotes (" ") on the screen.

Figure 8.6. File name and storage location.
Now open the command prompt and navigate to the directory where your java file is stored and type as in Figure 8.7. Pay attention to the way of writing and the results obtained.

Figure 8.7. How to execute a program in Java.
Before it can be executed, the program code (Main.java) must be compiled using the javac command as shown in Figure 8.7. After successful compilation, the program can be executed using the java command. The compilation process will produce a file named Main.class (check your directory with the dir command, and look for a file with the suffix .class). What we call in the java command is the file with the suffix class and no longer the source code ending in .java.
9. OOP Programming Exercises
In the previous examples and some explanations we have touched several times on classes and objects. However, we have not learned clearly what classes and objects actually are in Java. Classes and objects in Java are the implementation of the object-oriented programming principles that we have learned at the beginning of this chapter.

Class can be defined as a framework that defines variables, general methods of a particular object. In object-oriented programming, classes are not much different from primitive data types. The difference is, data types are used to declare normal variables, while classes are used to declare variables in the form of objects. Classes are still abstract.
9.1 Class Creation
In Java, classes are defined with the class keyword. The general form for defining a class is as follows:
class NamaKelas
tipe data1; tipe data2;
...
tipe dataN;
tipe method1 (daftar parameter) {
//blok kode untuk method1
}
tipe method2 (daftar parameter) {
//blok kode untuk method2
}
...
tipe methodN (daftar parameter) {
//blok kode untuk methodN
}
}Data or variables defined in a class are often referred to as instance variables. The values of these variables will be read through the available methods. Thus, the method is used as an interface between the class user and the data in the class. Recall the principle of encapsulation at the beginning of the chapter. Consider the following class example.
Example 8.22. Creating a simple class
class Siswa
{
String name; String alamat; int usia;
}In the code above we create a class named Student. There are three data in the class, namely name, address and age. We have not added a method here. Through the code above we have actually defined a new data type, namely Student. The program code above is just a template. This means that if you run the program above it will not produce anything. We need to create an actual object based on the class above. In the following way.
Example 8.23. Using classes
class Siswa {
String nama; String alamat;
int usia;
}
public class DataSiswa {
public static void main(String[] args) { Siswa siswa1 = new Siswa(); siswa1.nama = "Roni"; siswa1.alamat = "Mergosono Gg. 1 No. 34"; siswa1.usia = 23;
System.out.println("Nama :" + siswa1.nama);
System.out.println("Alamat :" + siswa1.alamat);
System.out.println("Usia :" + siswa1.usia);
}
}The program code above must be saved with the file name DataSiswa.java, open Siswa.java. This is because the main method is in the DataSiswa class. In the code above, we use the Siswa class in the DataSiswa class. We create an actual object from the Siswa class by typing Siswa siswa1 = new Siswa();. Siswa1 is the name of the actual object from the Siswa class. After that, we can use the variables or data in the siswa class. If run, the program code above will produce output as in Figure 8.13.

Figure 8.13. Results of execution of the DataSiswa class
Now we will make the class a little more complex by including methods in the class. Consider the following example.
Example 8.23. Creating classes that have methods
class Siswa {
String nama; String alamat; int usia; double nilaiMatematika; double nilaiBhsInggris; double nilaiBhsIndonesia;
double rerata;
// Menghasilkan nama dari Siswa
public String getNama(){ return nama;
}
// Mengubah nama siswa public void setNama( String temp ){
nama = temp;
}
// Menghitung rata -- rata nilai
public double getRerata(){
rerata = (
nilaiMatematika+nilaiBhsInggris+nilaiBhsIndonesia )/3;
return rerata;
}
}
public class DataSiswa {
public static void main(String[] args) { Siswa siswa1 = new Siswa(); siswa1.setNama("Rony"); siswa1.nilaiMatematika = 67; siswa1.nilaiBhsInggris = 87;
siswa1.nilaiBhsIndonesia = 59;
System.out.println("Nama :" +
siswa1.getNama());
System.out.println("Nilai Matematika :" + siswa1.nilaiMatematika);
System.out.println("Nilai Bahasa Inggris :" + siswa1.nilaiBhsInggris);
System.out.println("Nilai Bahasa Indonesia :" + siswa1.nilaiBhsIndonesia);
System.out.println("Rerata :" +
siswa1.getRerata());
}
}In the code above we extend the Siswa class by adding four variables namely nilaiMathematika, nilaiBhsInggris, nilaiBhsIndonesia and rerata. We also add three methods namely getNama, setNama and getRerata. getNama is a method to display the contents of the nama variable. setNama is a method to give a value to the nama variable. getRerata is a method to calculate the average value of three lessons and display the contents of the calculation results. Note how this method is used in the DataSiswa class. When run, we will get the output as in Figure 8.14.

Figure 8.14. Execute on classes that have methods.
There are several types of methods in a class, namely methods that do not return a value, methods that return a value and special methods, namely constructors. In general, we can equate these methods with procedures or functions (see Chapters 6 and 7). Consider the following examples.
Example 8.24. Creating a method without returning a value
Class Bangun { double panjang; double lebar;
// Mendefinisikan method void (tidak mengembalikan nilai)
void cetakLuas() {
System.out.println("Luas bangun = " +
(panjang * lebar));
}
}
class pakaiBangun {
public static void main(String[] args) {
Bangun b1, b2;
// instansiasi objek b1 = new Bangun(); b2 = new Bangun();
// mengisi data untuk objek b1 b1.panjang = 4; b1.lebar = 3;
// mengisi data untuk objek b2 b2.panjang = 6; b2.lebar = 5;
// memanggil method cetakLuas() untuk masing-masing objek b1.cetakLuas(); b2.cetakLuas();
}
}In the code above, the Bangun class has one method, namely cetakLuas. This method does not return a value. The final result of this method will be stored in the method. Compare with the following example
Example 8.25. Creating a method with a return value
Class Bangun { double panjang; double lebar;
// Mendefinisikan method yang mengembalikan nilai double hitungLuas() { double luas = panjang * lebar; return luas;
}
}
class pakaiBangun {
public static void main(String[] args) {
Bangun b1, b2;
// instansiasi objek b1 = new Bangun(); b2 = new Bangun();
// mengisi data untuk objek b1 b1.panjang = 4; b1.lebar = 3;
// mengisi data untuk objek b2 b2.panjang = 6; b2.lebar = 5;
// memanggil method hitungLuas() untuk masing-masing objek
System.out.println("Luas b1 = " + b1.hitungLuas());
System.out.println("Luas b2 = " + b2.hitungLuas());
}
}In example 8.25, we create a method hitungLuas that returns a value. Note that the method declaration no longer uses void but uses double which is the data type of the returned value. To return a value, the return keyword is used. Note the method call method from examples 8.24 and 8.25, what is different?
Methods can also have arguments just like functions or procedures. Consider the following example.
Example 8.26. Creating a method with arguments
class Bangun { double panjang; double lebar;
// method dengan argumen void isiData(double p, double l) { panjang = p;
lebar = l;
}
// method yang mengembalikan nilai double hitungLuas() { double luas = panjang * lebar; return luas;
}
}
class pakaiBangun {
public static void main(String[] args) {
Bangun b;
// instansiasi obyek
b = new Bangun();
// memanggil method isiData dan mengisi argumennya b.isiData(6,8);
// memanggil method hitungLuas() untuk objek b
System.out.println("Luas b = " + b.hitungLuas());
}
}In example 8.26, we add another method to the Bangun class, namely isiData. Because it does not return a value, we use void. This method has two arguments, namely p and l, which are used to hold the values that we will enter. Note how we use this method (see section b.isiData(6, 8)).
Constructor is a special method, is a method defined in a class and will be called automatically every time an object is defined (instantiated). Usually, constructor functions to initialize values for data contained in the class concerned. The name of the constructor method must be the same as the name of the class itself. Constructor does not have a return value and is not void. Consider the following example.
Example 8.27. Creating a class with a constructor
class Bangun { double panjang; double lebar;
// constructor dengan argumen
Bangun(double p, double l) { panjang = p;
lebar = l;
}
// method yang mengembalikan nilai double hitungLuas() { double luas = panjang * lebar; return luas;
}
}
class pakaiBangun {
public static void main(String[] args) {
Bangun b;
// instansiasi obyek
b = new Bangun();
// memanggil method isiData dan mengisi argumennya b.isiData(6,8);
// memanggil method hitungLuas() untuk objek b
System.out.println("Luas b = " + b.hitungLuas());
}
}The code above at first glance is the same as example 8.26, but is actually different. In this code there is a constructor with the same name as the class, namely Build. Constructors, like other methods, may or may not have arguments. In the example above, our Build constructor has arguments p and l.
9.2. Implementation of Inheritance
The principle of inheritance, in general, you have learned at the beginning of the chapter. Inheritance is a big advantage in object-oriented programming because a property or method that has been defined in a superclass is automatically inherited from all subclasses. So we may only need to define a method once in the superclass and then we can use it in the subclass. Consider the following example.
Example 8.28. Implementation of inheritance
class SuperA { private int a;
public void setSuperA(int nilai) { a = nilai; }
public int getSuperA() { return a;
}
}
// membuat kelas turunan (subclass) dari kelas A class SubB extends SuperA { private int b;
public void setSubB(int nilai) { b = nilai; }
public int getSubB() { return b;
}
}
class DemoKelasTurunan1 {
public static void main(String[] args) {
// melakukan instansiasi terhadap kelas B
SubB ObyekB = new SubB();
// mengeset nilai objek dari kelas B
ObyekB.setSuperA(50);
ObyekB.setSubB(200);
// mendapatkan nilai yang terdapat dalam objek dari kelas B
System.out.println("Nilai a : " + Obyek.getSuperA());
System.out.println("Nilai b : " + Obyek.getSubB());
}
}In the code above, the SuperA class is a super class that has one data, namely a, and two methods, namely setSuperA and getSuperA. The SubB class is derived from the SuperA class (note the declaration of the SubB extends SuperA class). The data and methods in the SuperA class will automatically be brought to the SubB class. So that the SubB class will have two data, namely a and b. Data a is the result of inheritance from the SuperA class while data b belongs to the SubB class itself. The methods in the SubB class will consist of four methods, namely setSuperA and getSuperA which are inherited from the SuperA class and the setSubB and getSubB classes which belong to the SubB class itself. Try typing the program above then run it and observe the results obtained. Consider the following other examples.
Example 8.29. Application of inheritance to calculate area and volume.
class Bangun { protected double panjang; protected double lebar;
// constructor default Bangun() { panjang = lebar = 0;
}
Bangun(double p, double l) { panjang = p;
lebar = l;
}
// method yang mengembalikan nilai public double hitungLuas() { double luas = panjang * lebar; return luas;
}
}
class Box extends Bangun {
private double tinggi;
// constructor class Box Box (int p, int l, int t) {
panjang = p; lebar = l; tinggi = t;
}
public double getTinggi() { return tinggi;
}
public double hitungVolume() { double volume = panjang * lebar * tinggi; return volume;
}
}
class inheritBangun {
public static void main(String[] args) {
Box kotak;
// instansiasi obyek
kotak = new Box(6, 8, 3);
// memanggil method hitungLuas(), getTinggi() dan hitung volume()
System.out.println("Luas salah satu sisi = " + kotak.hitungLuas());
System.out.println("Tinggi kotak = " + kotak.getTinggi());
System.out.println("Volume kotak = " + kotak.hitungVolume());
}
}The Bangun class above is the superclass while Box is the subclass. In the Bangun default constructor, the length and width values are initialized to 0. Note that in front of the declaration of the length and width variables in the Bangun class, the protected keyword is included, which means that classes derived from Bangun can still access the values of these variables, but those that do not have a derived relationship cannot access them.
In Box which is a subclass, one variable is added, namely tinggi with the addition of the private keyword followed by its data type. Private indicates that the tinggi variable can only be accessed within the Box class. The opposite of private is public, which means it can be accessed by anyone and from anywhere. In the Box class, we also add one method, namely hitungVolume(). In example 8.29 above, the object we created, namely kotak, is the result of an instantiation of the Box class. Because the Box class is derived from the Bangun class, we can access the hitungLuas() method which is inherited from the Bangun class. Of course, we can access the getTinggi() and hitungVolume() methods which are methods in the Box class. If we execute the program above, it will look like this.

Figure 8.15. Results of executing the Bangun and Box class programs.
9.3. Implementation of Overriding and Overloading
Sometimes, when we create a method in a subclass, we want to create a method with the same name as the method in the superclass but with a different implementation. For example, in the Bangun class in example 8.29, the hitungLuas() method is available. For example, we want to create a Segitiga subclass which is derived from the Bangun class. Then we want to create a hitungLuas() method whose implementation is no longer area = length x width but with the implementation of area = 0.5 x base x height. In this condition, the hitungLuas() method from the superclass will be covered by the method in the subclass. This is usually called overriding. Consider the following example.
Example 8.30. Implementation of overriding
class Bangun { // method umum
public double hitungLuas() {
System.out.println("Method belum terdefinisi"); Return 0;
}
}
class Segitiga extends Bangun {
private double alas;
private double tinggi;
Segitiga (int a, int t) {
alas = a; tinggi = t;
}
// overriding method hitungLuas() public double hitungLuas() { double luas = 0.5 * alas * tinggi; return luas;
}
}
class overridingBangun { public static void main(String[] args) {
Segitiga s;
// instansiasi obyek
s = new Segitiga(6, 8);
// memanggil method hitungLuas() dari subclass Segitiga System.out.println("Luas segitiga = " +
s.hitungLuas());
}
}In the example above, the Bangun class as the superclass has a hitungLuas() method, but we have not defined the contents of the method. In the Segitiga class, we override the hitungLuas() method to get the area value of the triangle. In the execution of the program above, what is run is the hitungLuas() method in the Segitiga subclass. The results of the program execution will appear as in Figure 8.16. If we want to continue running the hitungLuas() method in the Bangun class, we can call it with the super keyword. Change the hitungLuas() method in the Segitiga class with the following code.
public double hitungLuas() {
super.hitungLuas();
System.out.println();
double luas = 0.5 * alas * tinggi;
return luas;
}Run the program, then you will get results like Figure 8.17. Compare it with the previous execution results (Figure 8.16)

Figure 8.16. The result of overriding execution in the hitungLuas() method.

Figure 8.17. Results of executing overriding and super statements.
Overloading is similar to overriding in that it hides methods from the superclass. But it has a difference, namely, in overloading the method has the same name as the method in the parent class, but has a different argument list and implementation. While overriding, the method has the same name and argument list as the parent class and only the implementation is different. Consider the following example.
Example 8.31. Example of overloading
class Bangun { // method umum
public double hitungLuas() {
System.out.println("Method belum terdefinisi"); return 0;
}
}
class BujurSangkar extends Bangun {
private double sisi;
// overload method hitungLuas() public double hitungLuas(double sisi) {
double luas = sisi * sisi;
return luas;
}
}
class overloadBangun {
public static void main(String[] args) {
BujurSangkar b;
// instansiasi obyek
b = new BujurSangkar();
// memanggil method hitungLuas() dari subclass
BujurSangkar
System.out.println("Luas BujurSangkar = " +
b.hitungLuas(6));
}
}Note in the code above, the hitungLuas() method in the Bangun class has no arguments while in the BujurSangkar class it has an argument, namely sisi. This is what is called overloading. Compare it with the overriding examples in examples 8.29 and 8.30.
9.4 Implementation of Polymorphism
As explained at the beginning of the chapter, polymorphism is the ability of a method to translate into various actions. Actually, when you study overriding and overloading above, you have indirectly learned the basics of polymorphism theory. Polymorphism allows a superclass to define common methods for all its descendants. The descendant classes can implement these methods according to the characteristics of each class.
In examples 8.30 and 8.31 we have created a Bangun class which is a parent class that has a hitungLuas() method. This method is general. In example 8.30, we implement this method to find the area of a triangle in the Segitiga class. While in example 8.31, we implement this method to find the area of a BujurSangkar in the BujurSangkar class. Consider the following example.
Example 8.32. Application of polymorphism
class Bangun { public double hitungLuas() { System.out.println("Method umum"); return 0;
}
}
class BujurSangkar extends Bangun {
private double sisi;
BujurSangkar(int s) { sisi = s;
}
//overriding method hitungLuas() public double hitungLuas() { double luas = sisi * sisi; return luas;
}
}
class Segitiga extends Bangun { private double alas;
private double tinggi;
Segitiga (int a, int t) {
alas = a; tinggi = t;
}
// overriding method hitungLuas() public double hitungLuas() { double luas = 0.5 * alas * tinggi; return luas;
}
}
class Lingkaran extends Bangun { private double jarijari;
private final double PI = 3.1416;
Lingkaran(int r) { jarijari = r;
}
//overriding method hitungLuas() public double hitungLuas() { double luas = PI * jarijari * jarijari; return luas;
}
}
class DemoPolimorfisme2 {
public static void main(String[] args) {
Bentuk obyek;
BujurSangkar b = new BujurSangkar(12);
Segitiga s = new Segitiga(5, 6);
Lingkaran l = new Lingkaran(4);
// obyek mengacu pada objek BujurSangkar obyek = b;
// akan memanggil method yang terdapat pada
BujurSangkar
System.out.println("Luas bujursangkar : " + obyek.hitungLuas()); System.out.println();
// obyek mengacu pada objek Segitiga obyek = s;
// akan memanggil method yang terdapat pada Segitiga
System.out.println("Luas segitiga : " + obyek.hitungLuas()); System.out.println();
// obyek mengacu pada objek Lingkaran obyek = l;
// akan memanggil method yang terdapat pada Lingkaran
System.out.println("Luas lingkaran: " + obyek.hitungLuas()); System.out.println();
}
}In this example 8.32 we combine the previous examples to show how polymorphism is formed. The parent class is Bangun and has subclasses BujurSangkar, Segitiga and Lingkaran. All subclasses have a method hitungLuas() which is derived from the Bangun class. Note that although the method name hitungLuas() is present in all subclasses, its implementation is different depending on each subclass.
9.5 Using Packages and Interfaces
In some sections above, packages have been mentioned. Packages in JAVA mean grouping several classes and interfaces in one unit. This feature provides a way to organize classes and interfaces in large numbers and avoid chaos in class and file naming.
If you look closely at example 8.4 in the previous sub-chapter, you have actually used this package concept indirectly. In this example, we use the import statement to use classes in the Java.IO package. Java provides many packages that have been created by the Java development team. We can use these packages to make programming easier.
How to create a package is quite easy, we just use the keyword package followed by the name of the package we want as follows:
package NamaPaket;
PackageName is the name of the package that we will use to store the program code files and the compiled files. Java uses a directory system to store the packages that are created. If we create a package with the name PaketBangun, then we must create a directory with the exact same name, namely PaketBangun. And the package files and classes in one package must be stored in that directory. Consider the following example.
Example 8.33. Package creation
In this section we will create a package that is a modification of example 8.32. The name of the package we want to create is PaketBangun which has three class members, namely the BujurSangkar, Segitiga and Lingkaran classes. For the initial stage, create a directory named PaketBangun (in this example, we place this directory in D:\TestCode\Java\PaketBangun). Then successively create the following program code and save it with the name according to the class name in the PaketBangun directory. Note that at the beginning of the class code it always begins with the statement package PaketBangun;. This indicates that the class is a member of PaketBangun. File:
BujurSangkar.java
package PaketBangun; class BujurSangkar extends Bangun { private double sisi;
public BujurSangkar(int s) { sisi = s; }
public double hitungLuas() { double luas = sisi * sisi; return luas;
}
}
File : Segitiga.java
package PaketBangun; class Segitiga extends Bangun { private double alas;
private double tinggi;
public Segitiga (int a, int t) {
alas = a; tinggi = t;
}
public double hitungLuas() { double luas = 0.5 * alas * tinggi; return luas;
}
}Circle.java
package PaketBangun; class Lingkaran extends Bangun { private double jarijari;
private final double PI = 3.1416;
public Lingkaran(int r) { jarijari = r;
}
public double hitungLuas() { double luas = PI * jarijari * jarijari; return luas;
}
}After that, set the classpath as seen in the first sub-chapter. And compile the three files above so that the file results will be obtained as in Figure 8.18.

Figure 8.18. Compilation on three package member files.
After successful compilation, create a new file in the D:\TestCode\Java directory, for example named PakaiPaketBangun.java. Then type the following code in the file. Compile and run the program code.
//import seluruh kelas pada PaketBangun import PaketBangun.*;
class PakaiPaketBangun {
public static void main(String[] args) {
BujurSangkar b = new BujurSangkar(12);
Segitiga s = new Segitiga(5, 6);
Lingkaran l = new Lingkaran(4);
System.out.println("Luas bujursangkar : " +
b.hitungLuas()); System.out.println();
System.out.println("Luas segitiga : " +
s.hitungLuas()); System.out.println();
System.out.println("Luas lingkaran: " +
l.hitungLuas()); System.out.println();
}
}Pay attention to the way of writing to call the package. If we only need the Lingkaran class, then we need to write import PaketBangun.Lingkaran;. but if we need all the classes then we write it by import PaketBangun.*;. If we run this command then the result will be exactly the same as example 8.33. The difference is that in example 8.32 the classes are in one file. While in example 8.33 the classes are in their respective files and are then grouped using packages.
Interfaces in the Java programming language are very similar to classes, but without class attributes and have methods declared without content. Method declarations in an interface can be implemented by other classes. A class can implement more than one interface. Methods in an interface implemented in a class must be exactly the same as those in the interface. Interfaces are used if we want unrelated classes to implement the same methods. Consider the following example.
Example 8.34. Creating an interface
interface Bentuk {
public double luas();
public double volume();
}In this example, we create an interface named Shape that has two methods, namely area() and volume(). Note the writing of the interface. Both existing methods are declared without content. We can use this interface to create a new class and implement this interface in that class. Consider the following example.
Example 8.34. Use of interfaces
class Kubus implements Bentuk {
int x = 10;
public double luas( ) {
return (6 * x * x);
}
public double volume() {
return (x * x * x);
}
}
class Lingkaran implements Bentuk {
int radius = 10; public double luas() {
return (Math.PI * radius * radius);
}
public double volume() {
return 0;
}
}10. Summary
- Important concepts to understand in object-oriented programming are classes, objects, abstraction, encapsulation, inheritance and polymorphism.
- There are 8 basic data types in Java, namely boolean (for logical forms), char (for textual forms), byte, short, int, long (integral), double and float (floating point).
- The operators available in Java are arithmetic, relational, logical and bitwise operators.
- Program control structures for branching can be done with the statements if, if ... else, and if ...else ... if, while repetition can be done with for, while and do-while.
- Exception is an abnormal condition that occurs at runtime. Java provides try, throw, catch and finally mechanisms to handle exceptions.
- Thread is a part of a program that is independent of other parts and can be run together. Java allows us to organize threads according to our needs.
- Java fully supports the concepts of classes, inheritance, overriding, overloading, and polymorphism.
- A package is a collection of classes. While an interface is a class without attributes and has methods declared without content.
11. Practice Questions
1. Create a program to display the values of several variables that have the following data types and initial values:
- a. Float data type, initial value = 3.45.
- b. Char data type, initial value = B
- c. Data type int, initial value = 23
2. Create a program to calculate the average value of the following three variables: number1 = 56.3, number2 = 12 and number3 = 2.78.
3. Using the variables in no. 2, create a program to find the smallest value of the three variables.
4. Take three test scores from the user and calculate the average of the scores. Give the statement "Congratulations" on the output if the average score is greater than or equal to 60, otherwise give the output. Use BufferedReader to get input from the user, and System.out to output the results.
5. Create a program that prints your name a hundred times. Create three versions of this program using while loop, do while loop and for loop.
6. Using classes, create a program about school staff classes. This class is a superclass which has subclasses of teachers and administrative staff.
- The school staff class has variables name, address, number of children, start date of employment and rank. In addition, it also has a method for length of service (obtained from the current date minus the start date of employment) and a method for calculating basic salary. Basic salary is obtained from the value of basic salary plus length of service allowance, work rank allowance and child allowance. In addition, it has a method for calculating total salary that has not been defined.
- The teacher class, in addition to the variables and methods in its superclass, also has a variable for the field of expertise and a method for calculating teaching allowances obtained from the number of teaching hours multiplied by the wage per teaching hour. Define the method for calculating total salary as the sum of the basic salary and the teaching allowance.
- The administrative staff class, in addition to the variables and methods in its superclass, also has a variable for weekly working hours and a method for calculating overtime pay. Overtime pay is calculated if an administrative staff works more than 40 hours per week. The excess is overtime hours. Overtime pay = the number of overtime hours multiplied by the hourly overtime pay. Define the method for calculating total salary as the sum of the basic salary and the overtime pay.
