Manish Meena

Java – Packages

Java Packages Packages are used in Java in order to prevent naming conflicts, control access, make searching/locating and usage of classes, interfaces, enumerations, and annotations easier, etc. A Java package can be defined as a grouping of related types (classes, interfaces, enumerations, and annotations ) providing access protection and namespace management. Types of Java Packages Java packages are of two types: Some of the existing packages in Java are − Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career. User-defined Java Packages You can define your own packages to bundle groups of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related. Since the package creates a new namespace there won’t be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes. Creating a Java Package While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package. Compiling with Java Package To compile the Java programs with package statements, you have to use -d option as shown below. javac -d Destination_folder file_name.java Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder. Java Package Example Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces. Following package example contains interface named animals − /* File name : Animal.java */packageanimals;interfaceAnimal{publicvoideat();publicvoidtravel();} Now, let us implement the above interface in the same package animals − Open Compiler packageanimals;/* File name : MammalInt.java */publicclassMammalIntimplementsAnimal{publicvoideat(){System.out.println(“Mammal eats”);}publicvoidtravel(){System.out.println(“Mammal travels”);}publicintnoOfLegs(){return0;}publicstaticvoidmain(String args[]){MammalInt m =newMammalInt(); m.eat(); m.travel();}}interfaceAnimal{publicvoideat();publicvoidtravel();} Output Now compile the java files as shown below − $ javac -d . Animal.java $ javac -d . MammalInt.java Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below. You can execute the class file within the package and get the result as shown below. Mammal eats Mammal travels Importing Java Package If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax. Example Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class. packagepayroll;publicclassBoss{publicvoidpayEmployee(Employee e){ e.mailCheck();}} What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package. payroll.Employee importpayroll.*; importpayroll.Employee; Example packagepayroll;publicclassEmployee{publicvoidmailCheck(){System.out.println(“Pay received.”);}} Example packagepayroll;importpayroll.Employee;publicclassBoss{publicvoidpayEmployee(Employee e){ e.mailCheck();}publicstaticvoidmain(String[] args){Boss boss =newBoss();Employee e =newEmployee(); boss.payEmployee(e);}} Output Pay received. Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration. Directory Structure of a Java Package Two major results occur when a class is placed in a package − Here is simple way of managing your files in Java − Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example − // File Name : Car.javapackagevehicle;publicclassCar{// Class implementation. } Now, put the source file in a directory whose name reflects the name of the package to which the class belongs − ….\vehicle\Car.java Now, the qualified class name and pathname would be as follows − In general, a company uses its reversed Internet domain name for its package names. Example − A company’s Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory. Example − The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this − ….\com\apple\computers\Dell.java At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class. For example − // File Name: Dell.javapackagecom.apple.computers;publicclassDell{}classUps{} Now, compile this file as follows using -d option − $javac -d . Dell.java The files will be compiled as follows − .\com\apple\computers\Dell.class .\com\apple\computers\Ups.class You can import all the classes or interfaces defined in \com\apple\computers\ as follows − importcom.apple.computers.*; Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as − <path-one>\sources\com\apple\computers\Dell.java <path-two>\classes\com\apple\computers\Dell.class By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses. The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class

Java – Packages Read More »

Java – Overriding

In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final. Benefit of Overriding in Java The benefit of overriding is: ability to define a behavior that’s specific to the subclass type, which means a subclass can implement a parent class method based on its requirement. In object-oriented terms, overriding means to override the functionality of an existing method. Java Method Overriding Method overriding allows us to achieve run-time polymorphism and is used for writing specific definitions of a subclass method that is already defined in the superclass. The method is superclass and overridden method in the subclass should have the same declaration signature such as parameters list, type, and return type. Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career. Usage of Java Method Overriding Following are the two important usages of method overriding in Java: Example of Method Overriding in Java Let us look at an example. Open Compiler classAnimal{publicvoidmove(){System.out.println(“Animals can move”);}}classDogextendsAnimal{publicvoidmove(){System.out.println(“Dogs can walk and run”);}}publicclassTestDog{publicstaticvoidmain(String args[]){Animal a =newAnimal();// Animal reference and objectAnimal b =newDog();// Animal reference but Dog object a.move();// runs the method in Animal class b.move();// runs the method in Dog class}} Output Animals can move Dogs can walk and run In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object. Consider the following example − Example Open Compiler classAnimal{publicvoidmove(){System.out.println(“Animals can move”);}}classDogextendsAnimal{publicvoidmove(){System.out.println(“Dogs can walk and run”);}publicvoidbark(){System.out.println(“Dogs can bark”);}}publicclassTestDog{publicstaticvoidmain(String args[]){Animal a =newAnimal();// Animal reference and objectAnimal b =newDog();// Animal reference but Dog object a.move();// runs the method in Animal class b.move();// runs the method in Dog class b.bark();}} Output TestDog.java:26: error: cannot find symbol b.bark(); ^ symbol: method bark() location: variable b of type Animal 1 error This program will throw a compile time error since b’s reference type Animal doesn’t have a method by the name of bark. Rules for Method Overriding Java Method and Constructor Overriding In Java, each class has a different name and the constructor’s name is the same as the class name. Thus, we cannot override a constructor as they cannot have the same name. Java Method Overriding: Using the super Keyword When invoking a superclass version of an overridden method the super keyword is used. Example: Using the super Keyword Open Compiler classAnimal{publicvoidmove(){System.out.println(“Animals can move”);}}classDogextendsAnimal{publicvoidmove(){super.move();// invokes the super class methodSystem.out.println(“Dogs can walk and run”);}}publicclassTestDog{publicstaticvoidmain(String args[]){Animal b =newDog();// Animal reference but Dog object b.move();// runs the method in Dog class}} Output Animals can move Dogs can walk and run Manish Meena

Java – Overriding Read More »

Java – Methods

Java Methods A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. In this tutorial, we will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design. Creating a Java Method To create a Java method, there should be an access modifier followed by the return type, method’s name, and parameters list. Syntax to Create a Java Method Considering the following example to explain the syntax of a method − modifier returnType nameOfMethod (ParameterList){// method body} The syntax shown above includes − Example to Create a Java Method Here is the source code of the above defined method called minFunction(). This method takes two parameters n1 and n2 and returns the minimum between the two − /** the snippet returns the minimum between two numbers */publicstaticintminFunction(int n1,int n2){int min;if(n1 > n2) min = n2;else min = n1;return min;} Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career. Calling a Java Method For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value). The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when − The methods returning void is considered as call to a statement. Lets consider an example − System.out.println(“This is tutorialspoint.com!”); The method returning value can be understood by the following example − int result =sum(6,9); Example: Defining and Calling a Java Method Following is the example to demonstrate how to define a method and how to call it − Open Compiler publicclassExampleMinNumber{publicstaticvoidmain(String[] args){int a =11;int b =6;int c =minFunction(a, b);System.out.println(“Minimum Value = “+ c);}/** returns the minimum of two numbers */publicstaticintminFunction(int n1,int n2){int min;if(n1 > n2) min = n2;else min = n1;return min;}} Output Minimum value = 6 The void Keyword with Java Methods The void keyword allows us to create methods which do not return a value. Here, in the following example we’re considering a void method methodRankPoints. This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example. Example: Use of void keyword with Methods Open Compiler publicclassExampleVoid{publicstaticvoidmain(String[] args){methodRankPoints(255.7);}publicstaticvoidmethodRankPoints(double points){if(points >=202.5){System.out.println(“Rank:A1”);}elseif(points >=122.4){System.out.println(“Rank:A2”);}else{System.out.println(“Rank:A3”);}}} Output Rank:A1 Passing Parameters by Value in Java Methods While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference. Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter. Example: Passing Parameters by Value The following program shows an example of passing parameter by value. The values of the arguments remains the same even after the method invocation. Open Compiler publicclass swappingExample {publicstaticvoidmain(String[] args){int a =30;int b =45;System.out.println(“Before swapping, a = “+ a +” and b = “+ b);// Invoke the swap methodswapFunction(a, b);System.out.println(“\n**Now, Before and After swapping values will be same here**:”);System.out.println(“After swapping, a = “+ a +” and b is “+ b);}publicstaticvoidswapFunction(int a,int b){System.out.println(“Before swapping(Inside), a = “+ a +” b = “+ b);// Swap n1 with n2int c = a; a = b; b = c;System.out.println(“After swapping(Inside), a = “+ a +” b = “+ b);}} Output Before swapping, a = 30 and b = 45 Before swapping(Inside), a = 30 b = 45 After swapping(Inside), a = 45 b = 30 **Now, Before and After swapping values will be same here**: After swapping, a = 30 and b is 45 Java Methods Overloading When a class has two or more methods by the same name but different parameters, it is known as method overloading. It is different from overriding. In overriding, a method has the same method name, type, number of parameters, etc. Let’s consider the example discussed earlier for finding minimum numbers of integer type. If, let’s say we want to find the minimum number of double type. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters. The following example explains the same − Example: Methods Overloading in Java Open Compiler publicclassExampleOverloading{publicstaticvoidmain(String[] args){int a =11;int b =6;double c =7.3;double d =9.4;int result1 =minFunction(a, b);// same function name with different parametersdouble result2 =minFunction(c, d);System.out.println(“Minimum Value = “+ result1);System.out.println(“Minimum Value = “+ result2);}// for integerpublicstaticintminFunction(int n1,int n2){int min;if(n1 > n2) min = n2;else min = n1;return min;}// for doublepublicstaticdoubleminFunction(double n1,double n2){double min;if(n1 > n2) min = n2;else min = n1;return min;}} Output Minimum Value = 6 Minimum Value = 7.3 Overloading methods makes program readable. Here, two methods are given by the same name but with different parameters. The minimum number from integer and double types is the result. Using Command-Line Arguments Sometimes you will want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program’s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ). Example The following program displays all of the command-line arguments that it is called with − publicclassCommandLine{publicstaticvoidmain(String args[]){for(int i =0; i<args.length; i++){System.out.println(“args[“+ i +”]: “+ args[i]);}}} Try executing this program as shown here − $java CommandLine this is a command line 200 -100 Output args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100 The this Keyword inside Java Methods this is a keyword in

Java – Methods Read More »