Java For Beginners The Complete Guide To Learning Java for Beginners pdf pdf

AVA FOR EGINNERS

  J B HE OMPLETE UIDE O EARNING AVA FOR EGINNERS T C G T L J B

  

Bruce Berke

© 2018

  ฀ Copyright 2018 by Bruce Berke - All rights reserved.

  

This document is geared towards providing exact and reliable information in regards to the topic and

issue covered. The publication is sold with the idea that the publisher is not required to render

accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or

professional, a practiced individual in the profession should be ordered.

  • - From a Declaration of Principles which was accepted and approved equally by a Committee of the

    American Bar Association and a Committee of Publishers and Associations.

    In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic

    means or in printed format. Recording of this publication is strictly prohibited and any storage of this

    document is not allowed unless with written permission from the publisher. All rights reserved.

    The information provided herein is stated to be truthful and consistent, in that any liability, in terms of

    inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained

    within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any

    legal responsibility or blame be held against the publisher for any reparation, damages, or monetary

    loss due to the information herein, either directly or indirectly. Respective authors own all copyrights not held by the publisher.

    The information herein is offered for informational purposes solely, and is universal as so. The

    presentation of the information is without contract or any type of guarantee assurance.

    The trademarks that are used are without any consent, and the publication of the trademark is without

  

permission or backing by the trademark owner. All trademarks and brands within this book are for

clarifying purposes only and are the owned by the owners themselves, not affiliated with this

document.

  Table of Contents

  

  NTRODUCTION

  I Java is a wide programming language, packed with lots of features good for application development. It’s a good coding language for the design/development of desktop apps. These are popular as

standalone applications. If you need a distributed application, Java is the best language to use. Java

applets can be embedded/added on web pages. The many features offered by Java have made it a

popular coding language. Its wide features make it applicable in the development of apps applicable

in various industries. To code in Java, you should get the Java compiler. Java is compiled, not interpreted. You need an editor in which you can write your Java codes. Notepad is good for this.

With these, you can start writing and running your Java codes. This means it’s easy to get started with

Java, making Java a good language for beginners. The Java bytecode, normally generated after compiling Java source codes, is platform-independent, meaning it can be run on any platform including Windows, Solaris, Linux, etc. Java apps are secured via public-key cryptography, making them safe/secure. Java apps can be linked to various database management systems, for example, MySQL, Oracle, SQL Server, etc. This book is an excellent guide on Java programming. Get it and know every aspect of Java and transition from Java Beginner to Java Expert!

HAPTER 1: ETTING TARTED WITH JAVA

  C G S Java is a platform as well as a coding language. It is a robust, high-level, object-oriented and secured programming language. It was released in 1995 by the Sun Microsystems. Java treats

everything as an object. Its object model makes it easy to extend. The language is compiled, meaning

that we have a Java compiler. Java is also platform independent. After compiling your Java source

code, you get the byte code which can be executed on any platform. Java is also well known for being

easy to learn. If you know some basic concepts about object-oriented programming, it will be easy for you to learn Java. It is packed with numerous features, making it widely functional.

Authentication in Java is done using a public-key encryption, making its systems very secure. This is

the reason we can develop temper-free and virus-free systems with Java. In Java, errors are identified during the compile time, meaning that you cannot go to the run phase without first sorting out the error.

NVIRONMENT ETUP

  E S For you to write and run Java programs, you need a text editor and the Java compiler. The Java compiler comes with the JDK (Java Development Kit) which can be downloaded and installed for

free. You also need to have a text editor where you will be writing your Java programs. You can even

use a basic text editor like Notepad and it will be okay. However, there are advanced text editors for

Java such as Eclipse and Netbeans. First, download and install the JDK on your computer. After that, you will have installed Java on your machine. Open your browser then type or paste the following URL: From there, you can get the latest version of the JDK. You will then have to set the environment

variables to know the right Java installation directories. This means you should set the path variable.

  Mostly, the installation is done in the c:\Program Files\java\jdk directory. To set the path on Windows, correctly “My Computer”, choose “Properties”, open the “Advanced” tab then choose “Environment variables”. Add the “c:\Program Files\java\jdk\bin” path. For Linux users, read the documentation of your shell.

AVA YNTAX

  J S

A Java program consists of objects communicating via invocation of methods from each other. Below

are the main constructs in a Java program:

  Object- Objects are characterized by state and behavior. For example, a cat has states

like color, breed name and behaviors like eating, meowing and wagging tail.

Class- This is a blueprint/template describing the state/behaviors supported by its objects. Method- A method is a behavior. Logic is written in methods, and they are usable in data manipulation.

IRST ROGRAM

  F P This is our first Java program. It should print “Hello World” once executed:

  public class OurFirstProgram{ public static void main(String args[]){ System.out.println("Hello World"); } } Open your text editor like Notepad and create a new file named “FirstProgram.java. Save the file.

  

The .java extension marks the file as a Java file. Type the above program code in the file and save the

changes. Open the command prompt then navigate to the directory in which you have saved the file. Run the commands given below from that directory:

  javac FirstProgram.java java FirstProgram

  In my case, I saved the file on the desktop. I executed the commands as follows:

  

The program prints “Hello World” as the result. In the command “javac FirstProgram.java”, we are

invoking the java compiler (javac) to compile the program. The command returned nothing on the command prompt since the program has no error, and no warning was generated. The command generates a .class file (FirstProgram.class) in the directory; please confirm. In the command “java FirstProgram”, we are simply running the program to give us the result.

  Consider the following line extracted from the code:

  public class FirstProgram{

  

The line simply declares a class named FirstProgram. Java is a case sensitive language, hence this

class must always be referred to as it is written above. The “public” keyword declares that class as

public, meaning it is accessible from any other class within the same package. The { declares the beginning of the class body, and it should be closed by a }.

  Note: The filename in which we write the program should match the class-name; otherwise, you will experience trouble when running the program. In our case, the class was named “FirstProgram”, hence the filename should be FirstProgram.java.

  Consider the following line extracted from the code:

  public static void main(String args[]){

  

That’s the main method. A java program cannot be executed or run without this method. Consider the

following line extracted from the code:

  System.out.println("Hello World");

  

We are simply invoking or calling the “println” method to print the text Hello World on the terminal

of the command prompt.

  Lastly, we have two closing curly braces, }}. The first one closes the opening brace for the main method while the second one closes the opening brace for the class.

HAPTER 2: AVA ARIABLES

  C J

   V A variable can be seen as a container responsible for holding a value during the life of a program.

Each variable is of a certain data type, designative the kind of value that it can hold. There are two

steps in using Java variables, that is, variable declaration and variable initialization.

ARIABLE ECLARATION

  V D The declaration of a variable involves giving it a name and specifying its data type. Below are examples of valid variable declaration:

  int x,j,z; float pi; double a; char c;

  

The int, float, double and char are the data types, specifying the type of value each variable can or

should hold. To declare several variables in one line, separate them using a comma (,) as in the first

example. A variable declaration should end with a semicolon (;).

ARIABLE NITIALIZATION

  V

  I Variable initializing involves assigning it a valid value. The value to be assigned to the variable is determined by the variable’s data type. Below are examples of valid variable initializations.

  pi =3.14f; a =20.22778765; c=’v’;

  Both the declaration and initialization of a variable can be done at once as shown below:

  int x=1,z=4,y=5; float pi=3.14f; double d=19.12d; char c=’v’;

ARIABLE YPES

  V T

Java supports three variable types:

  1. Local Variables

  2. Static Variables

  3. Instance Variables

OCAL ARIABLES

  L

  V These are variables declared within a method body. They can only be accessed from within that method.

NSTANCE ARIABLES

  I

  V These are the variables that have been defined without the use of STATIC keyword. These variables are specific to an object.

TATIC ARIABLES

  S

  V These are variables initialized once at the beginning of the program execution. You should initialize them before instance variables.

  The following example demonstrates the different types of Java variables:

  class JavaVariables { int i = 10; //an instance variable static int b = 2; //a static variable void methodExample() { int c = 3; //a local variable } }

  The variable integer b is a static variable since it has been defined with the static keyword. The

variable int c has been declared within the methodExample method, making it a local variable. It can

only be accessed from within that method.

ATA YPES

  D T In Java, a data type can be either primitive or non-primitive.

  RIMITIVE ATA YPES P D T

These are the predefined data types that are already provided by Java. They are 8 in number including

byte, short, long, char, int, float, Boolean and double data types.

ON- RIMITIVE ATA YPES

  N P D T These are defined by the use of defined class constructors. They help programmers access objects.

  The example given below demonstrates the use of variables:

  public class VariableAddition{ public static void main(String[] args){ int ax=5; int jk=12; int z=ax+jk; System.out.println(z); } }

  

We have defined three integer variables x, j and z. The values for x and j have been initialized, while

the value for z is the addition of the previous two variables. We have then invoked the “println” function to print the value of z. It should print 17, the result of the addition of 5 and 12.

YPE ASTING AND YPE ONVERSION

  T C T C

It is possible for a variable of a particular type to get a value of some other type. Type conversion is

when a variable of a smaller capacity is assigned a variable of a bigger capacity. Example:

  double db; int x=5; db-x;

  Type casting is when a variable of a larger capacity is assigned some other variable of a smaller capacity. Example:

  db =5; int x; x= (int) db;

  The (int) is known as the type cast operator. If it is not specified, you get an error. Typecasting example:

  public class TypecastingExample{ public static void main(String[] args){ float ft=11.8f; //int x=ft;//a compile time error int x=(int)ft; System.out.println(ft); System.out.println(x); } }

HAPTER 3: AVA OPERATORS

  C J

Operators are symbols used to perform operations. For example, the + symbol is used for arithmetic

operations. Java supports different operators:

NARY PERATOR

  U O This is an operator that takes one operand. They increment/decrement a value. They include ++ (increment) and - -(decrement). Example:

  public class UnaryOperatorExample{ public static void main(String args[]){ int j=0; System.out.println(j++);//from 0 to 1 System.out.println(++j);//2 System.out.println(j--);//1 System.out.println(--j);//0 } }

  

The program will print 0, 2, 2, 0. The j++ means that the value of j is read first before the increment

is done, hence we got the value of j as 0. If it was ++j, then we would get a 1 as the first value of j.

You can try it.

RITHMETIC PERATORS

  A O These operators are used for performing mathematical operations like multiplication, addition, division, subtraction etc. They are used as mathematical operators. Example:

  public class JavaArithmeticOperatorsExample{ public static void main(String args[]){ int x=0; int y=10; System.out.println(x+y);//10 System.out.println(x-y);//-10 System.out.println(x*y);//0 System.out.println(x/y);//0 System.out.println(x%7);//0 } }

  

The only operator that may look unfamiliar is the % (modulus operator), which returns the remainder

after division.

OGICAL PERATORS

  L O These operators are used together with the binary values. They help in evaluation of conditions in

loops and conditional statements. They include ||, &&, !. Suppose we have two Boolean variables, a1

and a2, the following conditions apply: a1&&a2 will return true if both a1 and a2 are true; otherwise, they will return false. a1||a2 will return false if both a1 and a2 are false; otherwise, they will return true. !a1 will return opposite of a1. Example:

  public class LogicalOperatorExample { public static void main(String args[]) { boolean a1 = true; boolean a2 = false; System.out.println("a1 && a2: " + (a1&&a2)); System.out.println("a1 || a2: " + (a1||a2)); System.out.println("!(a1 && a2): " + !(a1&&a2)); } } The program will return false, true, true.

OMPARISON PERATORS

  C O Java supports 6 types of comparison operators, ==, !=, <, >, >=, <=: == will return true if both the left and right sides are equal.

  

!= will return true if the left and right sides of the operator are not equal.

  ฀ Returns true if the left side is greater than the right side. < returns true if the left side is less than the right side. >= returns true if the left side is greater than/equal to the right. <= returns true if the left side is less than the right side. Example:

  public class JavaRelationalOperatorExample { public static void main(String args[]) { int n1 = 20; int n2 = 30; if (n1==n2) { System.out.println("n1 and n2 are equal"); } else{ System.out.println("n1 and n2 aren’t equal"); } if( n1 != n2 ){ System.out.println("n1 and n2 aren’t equal"); } else{ System.out.println("n1 and n2 are equal"); } if( n1 > n2 ){ System.out.println("n1 is greater than n2"); } else{ System.out.println("n1 isn’t greater than n2");

   } if( n1 >= n2 ){ System.out.println("n1 is equal to or greater than n2"); } else{ System.out.println("n1 is less than n2"); } if( n1 < n2 ){ System.out.println("n1 is less than n2"); } else{ System.out.println("n1 isn’t less than n2"); } if( n1 <= n2){ System.out.println("n1 is equal to or less than n2"); } else{ System.out.println("n1 is greater than n2"); } } }

The program uses the if statement which is discussed in the next chapters.

HAPTER 4: AVA ARRAYS

  C J

Arrays are storage structures used for storing same-type elements. An array has a fixed size, which cannot be increased after definition. The first element in an array is at index 0. INGLE

IMENSIONAL RRAYS

  S D A

These are arrays in which the elements are stored linearly. The declaration of an array takes the

syntax given below:

  <elementDataType>[] <arrayName>;

  Another syntax:

  <elementDataType> <arrayName>[];

  Example:

  int arrayExample[]; int []arrayExample;

  An array can be initialized as follows:

  arrayExample[0]=1;

  

The line states that the element 1 should be stored at index 0 of the array. An array can also be

declared and initialized simultaneously as follows:

  int arrayExample[] = {5, 20, 35, 43}; The value 5 will be stored at the index 0 of the array 20 at index 1 and so on.

  Example:

  public class JavaArrayExample{ public static void main(String args[]){ int array1[] = new int[8]; for (int c=0;c<8;c++){ array1[c]=c+1; } for (int c=0;c<8;c++){ System.out.println("array1["+c+"] = "+array1[c]); } System.out.println("The Array Length = "+array1.length);

   } }

  

The array will print the elements contained at different indices. You will also get the array length,

which is 8.

  ULTI-

IMENSIONAL RRAYS

  M D A

These can be seen as arrays of other arrays. In multi-dimensional array declaration, you only add

another set of square brackets to define the other index. Example:

  int array2[ ][ ] = new int[6][10] ;

  You have the authority to control the length of your multi-dimensional array. Example:

  public class JavaArrayExample2 { public static void main(String[] args) { // Creating a 2-dimensional array. int[][] array2 = new int[6][8]; // Assign only three elements array2[0][0] = 2; array2 [1][1] = 12; array2 [3][2] = 11; System.out.print(array2[0][0] + " "); } } The program will return the value stored at index [0][0], which is 2.

HAPTER 5: ECISION MAKING

  C D

In Java, decision making helps us evaluate conditions and run statements based on the outcome of the

condition. Let us discuss the statements for decision making:

IF STATEMENT

  This statement has a Boolean expression and statement(s). Its syntax is given below:

  if(A_boolean_expression) { // Statement(s) to be run if true }

  

The statements within the body of the expression will run if the condition is true; otherwise, no result

from the program will run. Example:

  public class JavaIfStatement { public static void main(String args[]) { int marks = 20; if( marks < 50 ) { System.out.print("The marks is below 50"); } } }

  IF…ELSE STATEMENT

This statement combines an “if” with “else”, with the latter specifying the statement(s) to run if the

expression is found to be false. Syntax:

  if(A_boolean_expression) { // Statement(S) to run if expression is true }else { // Statement(s) to run if expression is false }

  Example:

  public class JavaIfElseStatement { public static void main(String args[]) { int marks = 30; if( marks < 50 ) { System.out.print("The marks is below 50"); }else { System.out.print("The marks is above 50"); } } }

  The first statement will be printed, that is, The marks is below 50. This is because the Boolean expression will be true. If it is false, the other statement will be printed. Example:

  public class JavaIfElseStatement { public static void main(String args[]) { int marks = 70; if( marks < 50 ) { System.out.print("The marks is below 50"); }else { System.out.print("The marks is above 50");

   } } }

  IF...ELSE

  IF...ELSE TATEMENT S

  

If you have several conditions to evaluate, use this statement. Syntax:

  if(A_boolean_expression a) { // Statement(s) }else if(A_boolean_expression b) { // Statement(s) }else if(A_boolean_expression c) { // Statement(s) }else { // Statement(s) }

  Example:

  public class JavaIfElseIfStatement { public static void main(String args[]) { int marks = 20; if( marks == 10 ) { System.out.print("Marks is 10"); }else if( marks == 20 ) { System.out.print("Marks is 20"); }else if( marks == 30 ) { System.out.print("Marks is 30"); }else { System.out.print("None of the above"); } } } The result from the program will be Marks is 20.

  ESTED

  IF N

  

The if…else statements can be nested, meaning that one may use an if inside another if or an if…else

inside another if…else. The nesting syntax is shown below:

  if(A_boolean_expression a) { // Statament(s) if(A_boolean_expression b) { // Statament(s) } }

  Example:

  public class NestingExample { public static void main(String args[]) { int ab = 10; int xy = 30; if( ab == 10 ) { if( xy == 30 ) { System.out.print("The value of ab is 10 and xy is 10"); } } } }

  

If the first condition becomes true, the second condition will evaluate. This is true in our case, hence

the println statement will be executed. If any of the conditions is false, then the println statement will not be executed.

SWITCH STATEMENT

  

This statement allows us to test a certain variable for equality against some values list. Every value

is referred to as case. The following syntax is used:

  switch(an_expression) { case value: // Statement(s) break; //optional case value: // Statement(s) break; //optional default : //Optional // Statement(s) }

  

The switch will terminate once it has reached the break statement. The flow will then jump to the

next line. However, note that it isn’t a must to add a break to every case. A default case may be added to the end of the switch, and this will run if none of the cases are true. Example:

  public class JavaSwitchStatement { public static void main(String args[]) { char student_grade = 'B'; switch(student_grade) { case 'A': System.out.println("That is Excellent!"); break; case 'B': System.out.println("That is Good!"); break; case 'C': System.out.println("That is Fair!");

   break; case 'D': System.out.println("That is Poor!"); case 'F': System.out.println("You Failed!"); break; default: System.out.println("Unknown grade"); } System.out.println("The student got grade " + student_grade); } }

  

The case for grade B will be true, so you will get the message for Good. After that, the program will

execute the last println statement, hence the value for student_grade will be printed.

HAPTER 6: LOOPING

  C

Java loops help us do some tasks repeatedly. Loops execute the statements in a sequential manner.

The first one is run first, followed by the second, etc. Let us discuss the Java loops:

FOR OOP

  L

The loop is run, provided the condition evaluates to true. The execution will stop immediately if the

condition becomes false. Syntax:

  for(initialization; loop_condition ; Increment/decrement_part) { the_statement(s); }

  

The initialization defines the initial value of the loop condition. The loop_condition specifies the

condition that must always be true for the loop to run. The loop_increment/decrement defines the amount by which the initialization value will be incremented or decremented after each iteration. Example:

  public class ForLoopDemo { public static void main(String args[]){ for(int ix=0; ix<10; ix++){ System.out.println("The ix value is currently: "+ix); } } }

  

The program will print the value of ix from 0 to 9. When the loop increments the 9 to get 10, it will

find that it is violating the loop condition, that is, ix<10, hence the execution will halt immediately.

WHILE OOP

  L

This loop executes the statement(s) as long as the specified condition is true. The condition is first

evaluated, and if true, the loop statement(s) are executed. If the condition becomes false, the control

will jump to execute statements that come after the loop. It is recommended you add an increment/decrement to the loop and a test condition so that the loop halts execution when the condition becomes false. Otherwise, the loop may run indefinitely. Syntax:

  while(A_boolean_expression) { // Statement(s) }

  Example:

  public class JavaWhileLoop { public static void main(String args[]) { int xy = 20; while( xy < 25 ) { System.out.print("The value of xy is: " + xy ); xy++; System.out.print("\n"); } } }

  

The program prints xy’s value from 20 to 24. The variable’s initial value is 20. The test condition

checks whether this value is less than 25, which is true. This means the loop will run. When it reached 24, it will check and find the value of xy is 25. The execution of the loop then halts immediately since continuing to execute it will violate the loop condition.

  DO…WHILE OOP L

  This is closely related to the while loop. In while, the loop condition execution is done before the loop body execution. This is opposite in a do…while loop as the body is executed first before the

condition. In a while loop, the loop body may never be executed, but in a do…while loop, the loop

body must be executed for at least once. Syntax:

  do { Statement or statements; } while(loop_condition);

  Example:

  public class JavaDoWhileLoopExample { public static void main(String args[]) { int xy = 20; do { System.out.print("The value of xy is: " + xy ); xy++; System.out.print("\n"); }while( xy < 25 ); } }

  The code will print the value of xy from 20 to 24 just as in the previous loop. This is because the

condition is true, that is, 20 is less than 25. Suppose we set the loop condition as false, for example,

initialize the value of xy to 30 as shown below:

  public class DoWhileLoopExample { public static void main(String args[]) { int xy = 30; do { System.out.print("The value of xy is: " + xy ); xy++; System.out.print("\n");

   }while( xy < 25 ); } }

  After running the above program, you will get “The value of xy is: 30” as the output. This means

that the while condition is false. This is because the Java compiler first runs through the program for

the initial value of xy which is 30. That value is printed. Once it moves to the loop condition, it finds itself violating the condition, that is, xy<25, hence the loop execution halts immediately.

  There are two statements that are used for controlling how Java loops are executed. They are

namely continue and break statements. They work by changing the normal way of executing a loop.

Let us discuss them.

BREAK TATEMENT

  S This statement causes the execution of a loop to halt, and the control jumps to the statement that comes next after the loop. It also halts a case in a switch statement. Syntax:

  your-jump-statement; break;

  Example:

  public class JavaBreakStatementExample { public static void main(String[] args) { for(int ix=0;ix<=10;ix++){ if(ix==6){ break; } System.out.println(ix); } } }

  The program will print from 0 to 5. This is because of the following section of our program:

  if(ix==6){ break;

  

The increment is done from 0 to 5, and once it notices that the value of ix is 6, it will halt immediately

as it will be violating the above condition. For the case of nested loops, the break can be added to the

inner loop, and it will break it. This will cause the inner loop to break once the specified condition is

met. Example:

   public class BreakStatement2 { public static void main(String[] args) { for(int ix=1;ix<=5;ix++){ for(int jk=1;jk<=5;jk++){ if(ix==3&&jk==3){ break; }

   } } } }

CONTINUE TATEMENT

  S

This statement makes the loop jump to next iteration immediately. It helps the loop to continue after a

jump. Note that in previous case, the loop halted immediately. This statement can help it resume execution in the next iteration after the jump. Example:

  your_jump-statement; continue;

  Example:

  public class ContinueStatamentExample { public static void main(String[] args) { for(int ix=1;ix<=10;ix++){ if(ix==5){ continue; } System.out.println(ix); } } } The code will not print 5, but all the other numbers from 1 to 10 will be printed.

  The continue statement may also be used with an inner loop. In such a case, it will only continue your inner loop. Example:

  public class ContinueStatament2 { public static void main(String[] args) { for(int ix=1;ix<=3;ix++){ for(int jk=1;jk<=3;jk++){ if(ix==2&&jk==2){ continue; } System.out.println(ix+" "+jk);

   } } } }

HAPTER 7: NHERITANCE

  C

  

I

In inheritance, an object acquires the behaviors and properties of another object. The object acquiring the behaviors and the properties is the child, while the object from which they are inherited is the parent. They can also be referred to as subclass and superclass respectively. Inheritance makes

information manageable in an hierarchical order. The methods that had been defined in the superclass

can be reused in the subclass without defining them again.

  

To inherit from a parent class, we use the extends keyword. Inheritance is done using the syntax given

below:

  class Child-class-name extends Parent-class-name { // fields and methods }

  The extends keyword is an indication that we are creating some new class from an existing class. Example:

  class CompanyEmployee{ float employee_salary=40000; } public class JavaProgrammer extends CompanyEmployee{ int bonus=10000; public static void main(String args[]){ JavaProgrammer p=new JavaProgrammer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } }

  There are different inheritance types:

INGLE NHERITANCE

  S

  I In this case, a single class inherits from another class. The Worker and DBA classes given previously are an example of this. Example:

   class Mammal{ void drink(){ System.out.println("Drinking..."); } } class Cow extends Mammal{ void moow(){System.out.println("Moowing...");} } public class JavaInheritanceTest{ public static void main(String args[]){ Cow c=new Cow(); c.moow(); c.drink(); } }

  In the above example, the drink() method has been defined in the Mammal class while the moow() method has been defined in the Cow class which extends the Mammal class. In the InheritanceTest class, we have created an instance of Cow class and named it c. We have then used this instance to

access the two methods that have been defined in two different classes. That is how single inheritance

works.

ULTILEVEL NHERITANCE

  M

  I This inheritance occurs when a class B inherits from class A, while class C inherits from class B. Example:

   class Mammal{ void drink(){ System.out.println("Drinking..."); } } class Cow extends Mammal{ void moow(){ System.out.println("Moowing..."); } } class BabyCow extends Cow{ void jump(){ System.out.println("Jumping...");} } public class JavaInheritanceTest2{ public static void main(String args[]){ BabyCow bc=new BabyCow(); bc.moow(); bc.jump(); bc.drink();

   } }

  

The drink() method has been defined in the Mammal class. The moow() method is defined in the Cow

class which extends the Mammal class. The jump method has been defined in the BabyCow class

which extends the Cow class. In the InheritanceTest2 class, we have created an instance of BabyCow

class named bc. This instance has then been used to access the various properties or methods. We are

able to use the instance of BabyCow class to access methods defined in the Cow and Mammal classes. The methods in various classes can be seen as their properties.

IERARCHICAL NHERITANCE

  H

  I This type of inheritance can be demonstrated like in this example:

   class Mammal{ void drink(){ System.out.println("Drinking..."); } } class Cow extends Mammal{ void moow(){ System.out.println("Moowing..."); } } class Goat extends Mammal{ void meew(){ System.out.println("Meewing..."); } } public class JavaInheritanceTest3{ public static void main(String args[]){ Goat g=new Goat(); g.meew();

   //g.moow(); will give an Error } }

  After creating an instance of Goat class in the InheritanceTest3 class, we are able to inherit the properties defined in the Mammal class since the Goat class inherits from the Mammal class.

However, we are unable to access the properties defined in the Cow class since the Goat class does

not inherit from the Cow class. If we attempt to do that, for example, run the g.moow(); statement, we

will get an error.

Some languages support multiple inheritance, in which a single class inherits from two classes. Java

doesn’t support this, and the closest we can get to this is by creating an interface, then use the

implements on the interface. Suppose we create an interface named Interface1, then we can create a

class named Class2 that extends from Class1 and implements the interface Interface1:

  public class Class2 extends Class1 implements Interface1{ }

  That is the closest we can get to the multiple inheritance feature in Java. For the class, we use the

keyword “extends”, but this cannot be used for an interface. Instead, we use the keyword implements.

This way, we can inherit the features of an interface. Inheritance helps in the reuse of existing properties and methods.

HAPTER 8: OVERRIDING

  C

A subclass can override a method defined in the parent class if it was not declared with the final

keyword. Overriding simply means overriding the functionality of the existing method. Example:

  class Mammal { public void drink() { System.out.println("Mammals can drink"); } } class Cow extends Mammal { public void drink() { System.out.println("Cows can drink and eat"); } } public class JavaTestOverriding { public static void main(String args[]) { Mammal a = new Mammal (); // Animal reference and object Mammal b = new Cow(); // Animal reference but Dog object a.drink(); // to execute the method of Mammal class b.drink(); // to execute the method of Cow class } }

  

In this case, b is a Mammal type, but it can use the method defined in the Cow class. Example 2:

We will give a bank example. Different banks offer different interest rates on loans:

   class Banks{ int getInterestRat(){ return 0;

   } } class Bank1 extends Banks{ int getInterestRat(){ return 5; } } class Bank2 extends Banks{ int getInterestRat(){ return 7; } } class Bank3 extends Banks{ int getInterestRat(){ return 9; } } public class TestBanks{ public static void main(String args[]){ Bank1 b1=new Bank1(); Bank2 b2=new Bank2(); Bank3 b3=new Bank3(); System.out.println("Bank1 Interest Rate: "+b1.getInterestRat()); System.out.println("Bank1 Interest Rate: "+b2.getInterestRat()); System.out.println("Bank1 Interest Rate: "+b3.getInterestRat()); } } The method has been used differently for different classes.

SUPER EYWORD

  K

We use the “super” keyword to access a method overridden from the super class. Example:

  class Mammals { public void drink() { System.out.println("Mammals can drink"); } } class Cow extends Mammals { public void drink() { super.drink(); // to invoke method in super class System.out.println("Cows can drink and eat"); } } public class TestCow { public static void main(String args[]) { Mammals c = new Cow(); // mammal reference but Cow object c.drink(); // to execute method in Cow class } }

HAPTER 9: OLYMORPHISM

  C P This feature allows us to perform an action through divergent ways. With polymorphism, one object may take different forms. Example:

  public interface Animals{} public class Mammals{} public class Cow extends Animals implements Mammals{ }