Packages and “this” Keyword
THIS KEYWORD
“This Keyword” -> refers current object
- The main purpose of using “this” Keyword is to differntiate the formal parameter and data memebers of class,whenever the formal parameter and data memebers are same the java virtual machine get ambiguity.
- To differntiate between formal parameter and data memebers of the class must proceded by “this”.
class Shop2{
String name1;
int price1;
public Shop2(String name1,int price1){
this.name1=name1;
this.price1=price1;
}
public static void main(String[] args)
{
Shop2 pro1 = new Shop2("abc",20);
Shop2 pro2 = new Shop2("cde",40);
Shop2 pro3 = new Shop2("ghf",2000);
System.out.println("product3 name:"+pro3.name1);
System.out.println("product2 price:" +pro2.price1);
}
}
//output
product3 name:ghf
product2 price:40
Note: /* non-static variablr “this” cannot be reffered in static context ( this -> current object)*/
Packages in Java:
Packages in java is a pack(group) of classes,interfaces and other packages. Packages are used in java in order to prevent naming conflicts, to control access,to make searching /locating and usage of classes,interfaces,easier,etc,.
SYNTAX:
package nameOfPackage;
Advantages of package:
- Package is used to categorize the classes and interface so that they can be easily maintained.
- It reduces memory space and execution time.
- Redundancy(repitition) of code is minimized
- Provides access protection
- removes naming collision
TYPES OF JAVA PACKAGE
- Built-in packages
- User-defined packages
1.Built-in Packages:

1.Built-in Packages:
These packages consist of a large number of classes which are a part of java API. Some of the commonly used buit-in packages.
- java.lang: Contains language support classes(e.g classes which defines primitive data types,math operator). This package is automatically imported.
- java.io: Contains classes for supportive input/output operations.
- java.util: Contains utility classes which implement data structure like linked list,etc.,
- java.applet: Contains class for creating applets.
- java.awt: Contains classes for implemeting GUI(buttons,menu,etc)
- java.net: Contains classes for supporting operations
2 User-defined packages:
These are the packages that are defined by the user.
If you are not using any IDE, you need to follow the syntax given below:
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
There are three ways to access the package from outside the package.
- import package.*;
- import package.classname;
- fully qualified name.
import package.classname;
Accesing Constructor:
output:
Constructor called from another package
no1:33
no2:55.9
Comments
Post a Comment