Learn Automation Testing Easily and become skilled Automation Tester
Pages
▼
Java Basic on Operators
How to Write Hello World in Java:
Ideally the first step should've been setting up Java on your computer, but I don't want to bore you with downloading and installing a bunch of software right at the beginning. For this example, you'll use https://replit.com/ as your platform.
First, head over to https://replit.com/ and create a new account if you don't already have one. You can use your existing Google/GitHub/Facebook account to login. Once logged in, you'll land on your home. From there, use the Create button under My Repls to create a new repl.
In the Create a Repl modal, choose Java as Template, set a descriptive Title such as HelloWorld and hit the Create Repl button.
A code editor will show up with an integrated terminal as follows:
On the left side is the list of files in this project, in the middle is the code editor, and on the right side is the terminal.
The template comes with some code by default. You can run the code by hitting the Run button. Go ahead and do that, run the program.
If everything goes fine, you'll see the words "Hello world!" printed on the right side. Congratulations, you've successfully run your first Java program.
What’s Going On in the Code?
The hello world program is probably the most basic executable Java program that you can possibly write – and understanding this program is crucial.
This line creates a Main class. A class groups together a bunch of related code within a single unit.
This is a public class, which means this class is accessible anywhere in the codebase. One Java source file (files with the .java extension) can contain only one top level public class in it.
This top level public class has to be named exactly the same as the source code filename. That's why the file named Main.java contains the main class in this project.
To understand why, click on the three dots in the list of files and click on the Show hidden files option.
This will unveil some new files within the project. Among them is the Main.class file. This is called a bytecode. When you hit the Run button, the Java compiler compiled your code from the Main.java file into this bytecode.
Now, modify the existing Hello World code as follows:
As you can see, a new class calledNotMainhas been added. Go ahead and hit theRunbutton once more while keeping your eyes on theFilesmenu.
A new bytecode namedNotMain.classhas showed up. This means that for every class you have within your entire codebase, the compiler will create a separate bytecode.
This creates confusion about which class is the entry-point to this program. To solve this issue, Java uses the class that matches the source code file name as the entry-point to this program.
Enough about the class, now let's look at the function inside it:
Thepublic static void main (String[] args)function is special in Java. If you have experience with languages like C, C++ or Go, you should already know that every program in those languages has a main function. The execution of the program begins from this main function.
In Java, you have to write this function as exactlypublic static void main (String[] args)otherwise it won't work. In fact, if you change it even a little bit Java will start to scream.
The return type has changed fromvoidtointand the function now returns0at the end. As you can see in the console, it says:
Error: Main method must return a value of type void in class Main, please
define the main method as:
public static void main(String[] args)
Listen to that suggestion and revert your program back to how it was before.
Themainmethod is apublicmethod and thestaticmeans, you can call it without instantiating its class.
Thevoidmeans that the function doesn't return any value and theString[] argsmeans that the function takes an array of strings as an argument. This array holds command line arguments passed to the program during execution.
TheSystem.out.printlnprints out strings on the terminal. In the example above,"Hello world!"has been passed to the function, so you getHello world!printed on the terminal.
In Java, every statement ends with a semicolon.Unlike JavaScript or Python, semicolons in Java are mandatory. Leaving one out will cause the compilation to fail.
That's pretty much it for this program. If you didn't understand every aspect of this section word by word, don't worry. Things will become much clearer as you go forward.
For now, remember that the top levelpublic classin a Java source file has to match the file name, and the main function of any Java program has to be defined aspublic static void main(String[] args
Once the download has finished, start the installer and go through the installation process by hitting the Next buttons. Finish it by hitting the Close button on the last page.
The installation process may vary on macOS and Linux but you should be able to figure it out by yourself.
Once the installation has finished, execute the following command on your terminal:
java --version
# java 18.0.2 2022-07-19
# Java(TM) SE Runtime Environment (build 18.0.2+9-61)
# Java HotSpot(TM) 64-Bit Server VM (build 18.0.2+9-61, mixed mode, sharing)
If it works, you've successfully install Java SE Development Kit on your computer. If you want to use OpenJDK instead, feel free to downloadMicrosoft Build of OpenJDKorAdoptiumand go through the installation process.
For the simple example programs that we're going to write in this article, it won't matter which JDK you're using. But in real life, make sure that your JDK version plays nicely with the type of project you're working on.
How to Install a Java IDE on Your Computer
When it comes to Java,IntelliJ IDEAis undeniably the best IDE out there. Even Google uses it as a base for theirAndroid Studio.
Once the download finishes, use the installer to install IntelliJ IDEA like any other software.
How to Create a New Project on IntelliJ IDEA
publicclassMain{publicstaticvoid main (String[] args){System.out.println("Hello World!");}}
What are the Primitive Data Types in Java?
At a high level, there are two types of data in Java. There are the "primitives types" and the "non-primitive" or "reference types".
Primitive types store values. For example,intis a primitive type and it stores an integer value.
A reference type, on the other hand, stores the reference to a memory location where a dynamic object is being stored.
There are eight primitive data types in Java.
TYPE
EXPLANATION
byte
8-bit signed integer within the range of -128 to 127
short
16-bit signed integer within the range of -32,768 to 32,767
int
32-bit signed integer within the range of -2147483648 to 2147483647
long
64-bit signed integer within the range of -9223372036854775808 to 9223372036854775807
float
single-precision 32-bit floating point within the range of 1.4E-45 to 3.4028235E38
double
double-precision 64-bit floating point within the range of 4.9E-324 to 1.7976931348623157E308
boolean
It can be eithertrueorfalse
char
single 16-bit Unicode character within the range of\u0000(or 0) to\uffff(or 65,535 inclusive)
Yeah yeah I know the table looks scary but don't stress yourself. You don't have to memorize them.
You will not need to think about these ranges very frequently, and even if you do, there are ways to print them out within your Java code.
However, if you do not understand what a bit is, I would recommendthis short articleto learn about binary.
You've already learned about declaring an integer in the previous section. You can declare abyte,short, andlongin the same way.
Declaring adoublealso works the same way, except you can assign a number with a decimal point instead of an integer:
publicclassMain{publicstaticvoidmain(String[] args){double gpa =4.8;System.out.println("My GPA is "+ gpa +".");}}
If you assign anintto thedouble, such as4instead of4.8, the output will be4.0instead of4, becausedoublewill always have a decimal point.
Sincedoubleandfloatare similar, you may think that replacing thedoublekeyword withfloatwill convert this variable to a floating point number – but that's not correct. You'll have to append aforFafter the value:
publicclassMain{publicstaticvoidmain(String[] args){float gpa =4.8f;System.out.println("My GPA is "+ gpa +".");}}
This happens because, by default, every number with a decimal point is treated as adoublein Java. If you do not append thef, the compiler will think you're trying to assign adoublevalue to afloatvariable.
As you can imagine,falsecan be treated as a no andtruecan be treated as a yes.
Booleans will become much more useful once you've learned about conditional statements. So for now, just remember what they are and what they can hold.
Thechartype can hold any Unicode character within a certain range.
Wrapper classes can wrap around primitive datatypes and turn them into reference types. Wrapper classes are available for all eight primitive data types.
PRIMITIVE TYPE
WRAPPER CLASS
int
Integer
long
Long
short
Short
byte
Byte
boolean
Boolean
char
Character
float
Float
double
Double
You can use these wrapper classes as follows:
publicclassMain{publicstaticvoid main (String[] args){Integer age =27;Double gpa =4.8;System.out.println(age);// 27System.out.println(gpa);// 4.8}}
All you have to do is replace the primitive data type with the equivalent wrapper class. These reference types also have methods for extracting the primitive type from them.
For example,age.intValue()will return the age as a primitive integer and thegpa.doubleValue()will return the GPA in a primitive double type.
There are such methods for all eight datatypes. Although you'll use the primitive types most of the time, these wrapper classes will be handy in some scenarios we'll discuss in a later section.
How to Use Operators in Java
Operators in programming are certain symbols that tell the compiler to perform certain operations such as arithmetic, relational, or logical operations.
Although there are six types of operators in Java, I won't talk about bitwise operators here. Discussing bitwise operators in a beginner guide can make it intimidating.
You've already seen the usage of the+operator to sew strings together or format them in a specific way.
That approach works until you have a lot of additions to a string. It's easy to mess up the placements of the quotation marks.
A better way to format a string is theString.format()method.
publicclassMain{publicstaticvoidmain(String[] args){String name ="Farhan";int age =27;String formattedString =String.format("My name is %s and I'm %d years old.", name, age);System.out.println(formattedString);}}
The method takes a string with format specifiers as its first argument and arguments to replace those specifiers as the later arguments.
In the code above, the%s, and%dcharacters are format specifiers. They're responsible for telling the compiler that this part of the string will be replaced with something.
Then the compiler will replace the%swith thenameand the%dwith theage. The order of the specifiers needs to match the order of the arguments and the arguments need to match the type of the specifier.
The%sand%dare not random. They are specific for string data and decimal integers. A chart of the commonly used specifiers are as follows:
SPECIFIER
DATA TYPE
%b,%B
Boolean
%s,%S
String
%c,%C
Unicode Character
%d
Decimal Integer
%f
Floating Point Numbers
There is also%ofor octal integers,%xor%Xfor hexadecimal numbers, and%eor%Efor scientific notations. But since, we won't discuss them in this book, I've left them out.
Just like the%sand%dspecifiers you saw, you can use any of these specifiers for their corresponding data type. And just in case you're wondering, that%fspecifier works for both floats and doubles.
How to Get the Length of a String or Check if It's Empty or Not
Checking the length of a string or making sure its not empty before performing some operation is a common task.
Every string object comes with alength()method that returns the length of that string. It's like thelengthproperty for arrays.
publicclassMain{publicstaticvoidmain(String[] args){String name ="Farhan";System.out.println(String.format("Length of this string is: %d.", name.length()));// 6}}
The method returns the length as an integer. So you can freely use it in conjunction with the integer format specifier.
To check if a string is empty or not, you can use theisEmpty()method. Like thelength()method, it also comes with every string object.
publicclassMain{publicstaticvoidmain(String[] args){String name ="Farhan";if(name.isEmpty()){System.out.println("There is no name mentioned here");}else{System.out.println(String.format("Okay, I'll take care of %s.", name));}}}
The method returns a boolean value so you can use it directly in if statements. The program checks if the name is empty or not and prints out different responses based off of that.
How to Split and Join Strings
Thesplit()method can split a string based on a regular expression.
importjava.util.Arrays;publicclassMain{publicstaticvoidmain(String[] args){String name ="Farhan Hasin Chowdhury";System.out.println(Arrays.toString(name.split(" ")));}}
The method returns an array of strings. Each string in that array will be a substring from the original string. Here for example, you're breaking the stringFarhan Hasin Chowdhuryat each space. So the output will be[Farhan, Hasin, Chowdhury].
Just a reminder that arrays are collections of multiple data of the same type.
Since the method takes a regex as argument, you can use regular expressions to perform more complex split operations.
You can also join this array back into a string like this:
Converting a string to upper or lower case is very straightforward in Java. There are the aptly namedtoUpperCase()andtoLowerCase()methods to perform the tasks:
How to Replace Characters or Substrings in a String
Thereplace()method can replace characters or entire substrings from a given string.
packagestrings;publicclassMain{publicstaticvoidmain(String[] args){String loremIpsumStd ="Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.";System.out.println(String.format("Standard lorem ipsum text: %s", loremIpsumStd));String loremIpsumHalfTranslated = loremIpsumStd.replace("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium","But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system");System.out.println(String.format("Translated lorem ipsum text: %s", loremIpsumHalfTranslated));}}
Here, theloremIpsumStdstring contains a portion of the original lorem ipsum text. Then you're replacing the first line of that string and saving the new string in theloremIpsumHalfTranslatedvariable.
How to Check If a String Contains a Substring or Not
Thecontains()method can check whether a given string contains a certain substring or not.
publicclassMain{publicstaticvoidmain(String[] args){String lyric ="Roses are red, violets are blue";if(lyric.contains("blue")){System.out.println("The lyric has the word blue in it.");}else{System.out.println("The lyric doesn't have the word blue in it.");}}}
The method returns a boolean value, so you can use the function in any conditional statement.
There were some of the most common string methods. If you'd like to learn about the other ones, feel free to consultthe official documentation.
What Are the Different Ways of Inputting and Outputting Data?
importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[] args){Scanner scanner =newScanner(System.in);System.out.print("What's your name? ");String name = scanner.nextLine();System.out.printf("So %s. How old are you? ", name);int age = scanner.nextInt();System.out.printf("Cool! %d is a good age to start programming.", age);
scanner.close();}}
How to Use Conditional Statements in Java
publicclassMain{publicstaticvoidmain(String[] args){int age =20;// if (condition) {...}if(age >=18&& age <=40){System.out.println("you can use the program");}}}
What is a switch-case statement?
importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[] args){Scanner scanner =newScanner(System.in);System.out.print("What is the first operand? ");int a =scanner.nextInt();// consumes the dangling newline character
scanner.nextLine();System.out.print("What is the second operand? ");int b = scanner.nextInt();// consumes the dangling newline character
scanner.nextLine();System.out.print("What operation would you like to perform? ");String operation = scanner.nextLine();switch(operation){case"sum":System.out.printf("%d + %d = %d", a, b, a+b);break;case"sub":System.out.printf("%d - %d = %d", a, b, a-b);break;case"mul":System.out.printf("%d * %d = %d", a, b, a*b);break;case"div":if(b ==0){System.out.print("Can't divide by zero!");}else{System.out.printf("%d / %d = %d", a, b, a / b);}break;default:System.out.printf("Invalid Operation!");}
scanner.close();}}
What is Variable Scope in Java?
publicclassMain{publicstaticvoidmain(String[] args){int age =20;if(age >=18&& age <=40){// age variable is accessible here// booleans are not accessible hereboolean isSchoolStudent =true;boolean isLibraryMember =false;if(isSchoolStudent || isLibraryMember){// booleans are accessible here// age variable is accessible hereSystem.out.println("you can use the program");}}else{// age variable is accessible here// booleans are not accessible hereSystem.out.println("you can not use the program");}}}
What Are Default Values of Variables in Java?
publicclassMain{// gets 0 as the value by defaultstaticint age;publicstaticvoidmain(String[] args){System.out.println(age);// 0}}
How to Work with Arrays in Java
publicclassMain{publicstaticvoidmain(String[] args){// <type> <name>[] = new <type>[<length>]char vowels[]=newchar[5];}}
How to Sort an Array
importjava.util.Arrays;publicclassMain{publicstaticvoidmain(String[] args){char vowels[]={'e','u','o','i','a'};Arrays.sort(vowels);System.out.println("The sorted array: "+Arrays.toString(vowels));// [a, e, i, o , u]}}
How to Perform Binary Search on an Array
publicclassMain{publicstaticvoidmain(String[] args){char vowels[]={'a','e','i','o','u'};char key ='i';int foundItemIndex =Arrays.binarySearch(vowels, key);System.out.println("The vowel 'i' is at index: "+ foundItemIndex);// 2}}
If you ever need to repeat a task for a set number of times, you can use a loop. Loops can be of three types: they areforloops,for...eachloops, andwhileloops.
For Loop
publicclassMain{publicstaticvoidmain(String[] args){int fibonacciNumbers[]={0,1,1,2,3,5,8,13,21,34,55};for(int index =0; index < fibonacciNumbers.length; index++){System.out.println(fibonacciNumbers[index]);}}}
For-Each Loop
publicclassMain{publicstaticvoidmain(String[] args){int fibonacciNumbers[]={0,1,1,2,3,5,8,13,21,34,55};for(int number : fibonacciNumbers){System.out.println(number);}}}
While Loop
If you want to execute a bunch of code until a certain condition is met, you can use a while loop.
There are no initialization or update steps in a while loop. Whatever happens, happens within the loop body. If you rewrite the program for printing out the multiplication table of 5 using a while loop, it'll be as follows:
public class Main {
public static void main(String[] args) {
int number = 5;
int multiplier = 1;
while (multiplier <= 10) {
System.out.println(String.format("%d x %d = %d", number, multiplier, number*multiplier));
multiplier++;
}
}
}
// 5 x 1 = 5
// 5 x 2 = 10
// 5 x 3 = 15
// 5 x 4 = 20
// 5 x 5 = 25
// 5 x 6 = 30
// 5 x 7 = 35
// 5 x 8 = 40
// 5 x 9 = 45
// 5 x 10 = 50
Although, while loops are not as common as for loops in the real world, learning about them is worth it.
Do-While Loop
The final type of loop you'll learn about is the do-while loop. It kind of reverses the order of the regular while loop – so instead of checking the condition before executing the loop body, you execute the loop body first and then check the condition.
The multiplication table code implemented using a do-while loop will be as follows:
publicclassMain{publicstaticvoidmain(String[] args){int number =5;int multiplier =1;do{System.out.println(String.format("%d x %d = %d", number, multiplier, number*multiplier));
multiplier++;}while(multiplier <=10);}}// 5 x 1 = 5// 5 x 2 = 10// 5 x 3 = 15// 5 x 4 = 20// 5 x 5 = 25// 5 x 6 = 30// 5 x 7 = 35// 5 x 8 = 40// 5 x 9 = 45// 5 x 10 = 50
Do-while loops are very useful when you need to perform some operation until the user gives a specific input. Such as, show a menu until user presses the "x" key.
TheremoveIf()method can remove elements from an array list if they meet a certain condition:
importjava.util.ArrayList;publicclassMain{publicstaticvoid main (String[] args){ArrayList<Integer> numbers =newArrayList<>();for(int i =0; i <=10; i++){
numbers.add(i);}System.out.println(numbers.toString());// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.removeIf(number -> number %2==1);System.out.println(numbers.toString());// [0, 2, 4, 6, 8, 10]}}
The method takes a lambda expression as a parameter. Lambda expressions are like unnamed methods. They can receive parameters and work with them.
Here, theremoveIf()method will loop over the array list and pass each element to the lambda expression as the value of thenumbervariable.
Then the lambda expression will check whether the given number is divisible by 2 or not and returntrueorfalsebased on that.
If the lambda expression returnstrue, theremoveIf()method will keep the value. Otherwise the value will be deleted.
How to Clone and Compare Array Lists
importjava.util.ArrayList;publicclassMain{publicstaticvoid main (String[] args){ArrayList<Integer> numbers =newArrayList<>();for(int i =0; i <=10; i++){
numbers.add(i);}ArrayList<Integer> numbersCloned =(ArrayList<Integer>)numbers.clone();System.out.println(numbersCloned.equals(numbers));// true}}
How to Check if an Element Is Present or the Array List Is Empty
You can use thecontains()method to check if an array list contains a given element or not:
Comparators have other usages as well but those are out of the scope of this book.
How to Keep Common Elements From Two Array Lists
Think of a scenario where you have two array lists. Now you'll have to find out which elements are present in both array lists and remove the rest from the first array list.
TheretainAll()method can get rid of the uncommon elements from the first array list for you. You'll need to call the method on the array list you want to operate on and pass the second array list as a parameter.
How to Perform an Action on All Elements of an Array List
You've already learned about looping in previous sections. Well, array lists have aforEach()method of their own that takes a lambda expression as parameter and can perform an action on all the elements of the array list.
importjava.util.ArrayList;publicclassMain{publicstaticvoid main (String[] args){ArrayList<Integer> oddNumbers =newArrayList<>();
oddNumbers.add(1);
oddNumbers.add(3);
oddNumbers.add(5);
oddNumbers.add(7);
oddNumbers.add(9);
oddNumbers.forEach(number ->{
number = number *2;System.out.printf("%d ", number);// 2 6 10 14 18});System.out.println(oddNumbers.toString());// [1, 3, 5, 7, 9]}}
Last time, the lambda expression you saw was a single line – but they can be bigger. Here, theforEach()method will loop over the array list and pass each element to the lambda expression as the value of thenumbervariable.
The lambda expression will then multiply the supplied value by 2 and print it out on the terminal. However, the original array list will be unchanged.
How to Work With Hash Maps in Java
Hash maps in Java can store elements in key-value pairs. This collection type is comparable to dictionaries in Python and objects in JavaScript.
To create hash maps, you'll first have to import thejava.util.HashMapclass at the top of your source file.
Then you start by writingHashMapand then inside a pair of less than-greater than signs, you'll write the data type for the key and the value.
Here, the keys will be strings and values will be doubles. After that the assignment operator, followed bynew HashMap<>().
You can use theput()method to put a record in the hash map. The method takes the key as the first parameter and its corresponding value as the second parameter.
There is also theputIfAbsent()method that adds the given element only if it already doesn't exist in the hash map.
There is another variation of the this method. ThegetOrDefault()method works likeget()but if the given key is not found, it'll return a specified default value.
Difference between the two methods is that thecontainsKey()method checks if the given key exists or not and thecontainsValue()method checks if the given value exists or not.
And if you want to check if a hash map is empty or not, you can do so by using theisEmpty()method:
Since the method returns a boolean value, you can use it within if-else statements.
How to Perform an Action on All Elements of a Hash Map
Like the array lists, hash maps also have their ownforEach()method that you can use to loop over the hash map and repeat a certain action over each entry.
importjava.util.HashMap;publicclassMain{publicstaticvoid main (String[] args){HashMap<String,Double> prices =newHashMap<>();
prices.put("apple",2.0);
prices.put("orange",1.8);
prices.put("guava",1.5);
prices.put("berry",2.5);
prices.put("banana",1.0);System.out.println("prices after discounts");
prices.forEach((fruit, price)->{System.out.println(fruit +" - "+(price -0.5));});}}// prices after discounts// orange - 1.3// banana - 0.5// apple - 1.5// berry - 2.0// guava - 1.0
The method loops over each entry and passes the key and value to the lambda expression. Inside the lambda expression body, you can do whatever you want.
Classes and Objects in Java
importjava.time.LocalDate;publicclassMain{publicstaticvoid main (String[] args){User user =newUser();
user.name ="Farhan";
user.birthDay =LocalDate.parse("1996-07-15");System.out.printf("%s was born on %s.", user.name, user.birthDay.toString());// Farhan was born on 15th July 1996.}}
What is a Method?
importjava.time.LocalDate;publicclassMain{publicstaticvoid main (String[] args){User user =newUser();
user.name ="Farhan";
user.birthDay =LocalDate.parse("1996-07-15");System.out.printf("%s is %s years old.", user.name, user.age());// Farhan a 26 years old.}}
What is Method Overloading?
In Java, multiple methods can have the same name if their parameters are different. This is called method overloading.
One example can be theborrow()method on theUserclass. Right now, it accepts a single book as its parameter. Let's make an overloaded version which can accept an array of books instead.
ThegetName()andgetBorrowedBooks()are responsible for returning the value of thenameandborrowedBooksvariables.
You never actually access the birthday variable out of theage()method, so a getter is not necessary.
Since the type of theborrowedBooksvariable is not a concern of theMainclass, the getter makes sure to return the value in the proper format.
Now update the code in theMain.javafile to make use of these methods:
publicclassMain{publicstaticvoid main (String[] args){User user =newUser("Farhan","1996-07-15");Book book =newBook("Carmilla",newString[]{"Sheridan Le Fanu"});
user.borrow(book);System.out.printf("%s has borrowed these books: %s", user.getName(), user.getBorrowedBooks());}}
Excellent. It has become even cleaner and easier to read. Like getters, there are setters for writing values to the private properties.
For example, you may want to allow the user to change their name or birthday. Theborrow()method already works as a setter for theborrowedBooksarray list.
Now you can not access those properties directly. Instead you'll have to use one of the getters or setters.
What is Inheritance in Java?
Inheritance is another big feature of object oriented programming. Imagine you have three kinds of books. The regular ones, e-books, and audio books.
Although they have similarities such as title and author, they also have some differences. For example, the regular books and e-books have page count whereas audio books have run time. The e-books also have format such as PDF or EPUB.
So using the same class for all three of them is not an option. That doesn't mean you'll have to create three separate classes with minor differences, though. You can just create separate classes for e-books and audio books and make them inherit the properties and methods from theBookclass.
Let's begin by adding the page count in theBookclass:
importjava.util.ArrayList;importjava.util.Arrays;publicclassBook{privateString title;privateint pageCount;privateArrayList<String> authors =newArrayList<String>();Book(String title,int pageCount,String[] authors){this.title = title;this.pageCount = pageCount;this.authors =newArrayList<String>(Arrays.asList(authors));}publicStringlength(){returnString.format("%s is %d pages long.",this.title,this.pageCount);}publicStringtoString(){returnString.format("%s by %s",this.title,this.authors.toString());}}
Since you're not going to use getters and setters in these examples, cleaning up seemed like a good idea. Thelength()method returns the length of the book as a string.
Now create a new Java class namedAudioBookand put the following code in it:
Theextendskeyword lets the compiler know that this class is a subclass of theBookclass. This means that this class inherits all the properties and methods from the parent class.
Inside theAudioBookconstructor method, you set the run time for the audio book which is fine – but you'll also have to manually call the constructor of the parent class.
Thesuperkeyword in Java refers to the parent class, sosuper(title, 0, authors)essentially calls the parent constructor method with the necessary parameters.
Since the audio books don't have any pages, setting the page count to zero can be an easy solution.
Or you can create an overloaded version of theBookconstructor method that doesn't require the page count.
Next, create another Java class namedEbookwith the following code:
This class is largely identical to theBookclass except the fact that it has a format property.
publicclassMain{publicstaticvoid main (String[] args){Book book =newBook("Carmilla",200,newString[]{"Sheridan Le Fanu"});Ebook ebook =newEbook("Frankenstein",220,newString[]{"Mary Shelley"},"EPUB");AudioBook audioBook =newAudioBook("Dracula",newString[]{"Bram Stoker"},160);System.out.println(book.toString());// Carmilla by [Sheridan Le Fanu]System.out.println(ebook.toString());// Frankenstein by [Mary Shelley]System.out.println(audioBook.toString());// Dracula by [Bram Stoker]}}
So far everything is working fine. But do you remember thelength()method you wrote inside theBookclass? It'll work for the regular books but will break in the e-books.
That's because the page count property is marked asprivateand no other class exceptBookwill be able to access it. The title is also aprivateproperty.
Open theBook.javafile and mark thetitleandpageCountproperties as protected.
importjava.util.ArrayList;importjava.util.Arrays;publicclassBook{protectedString title;protectedint pageCount;privateArrayList<String> authors =newArrayList<String>();Book(String title,int pageCount,String[] authors){this.title = title;this.pageCount = pageCount;this.authors =newArrayList<String>(Arrays.asList(authors));}publicStringlength(){returnString.format("%s is %d pages long.",this.title,this.pageCount);}publicStringtoString(){returnString.format("%s by %s",this.title,this.authors.toString());}}
This'll make them accessible from the subclasses. The audio books have another problem with thelength()method.
Audio books don't have a page count. They have run times and this difference will break the length method.
One way to solve this problem is by overriding thelength()method.
How to Override a Method in Java
As the name suggests, overriding means cancelling the effect of a method by replacing it with something else.
You override a method from the parent class by rewriting the method in the subclass. The@Overridekeyword is an annotation. Annotations in Java are metadata.
It's not mandatory to annotate the method like this. But if you do, the compiler will know that the annotated method overrides a parent method and will make sure you're following all the rules of overriding.
For example, if you make a mistake in the method name and it doesn't match any method from the parent, the compiler will let you know that the method is not overriding anything.
publicclassMain{publicstaticvoid main (String[] args){AudioBook audioBook =newAudioBook("Dracula",newString[]{"Bram Stoker"},160);System.out.println(audioBook.length());// Dracula is 160 minutes long.}}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.