• Articles
  • Tutorials
  • Interview Questions

OOPs Concepts in Java with Real-World Examples

Tutorial Playlist

Object Oriented Programming in Java

This topic is about Java OOPs concept. After going through the Java basics such as arrays, language fundamentals, etc. you can start with the OOPs concept.

Watch this Java video by Intellipaat:

This topic is to introduce the concept of reusability, to provide security and many more features in Java.
Here is the list of topics if you directly want to jump:

Features of OOPs:
features of OOPs

Learn more about Java Certification from this insightful Java Certification blog!

Classes and Objects in Java

Let’s discuss the Classes and Objects in Java

Object: An Object is comprised of three parts: state, behaviour and identity.
An object is a logical or physical entity that tells about the state, behaviour and identity.
Example:
arr[0][0]=1;
classes and objects
In the above picture, we can understand about the object, state, behaviour and identity.

State: A state reflects the properties of an object.
Example: studying, cancelled, empty, etc.

Behaviour: Behaviour reflects the qualities of an object.
Example: eat, shrink, speak, etc.

Identity: Identity uniquely defines the object.
Example: Intellipaat, Hussain, etc.

class Intellipaat{ // Intellipaat is an object
void show(int e, String s){ // behaviour
System.out.println(s+” ”+e);
}
public static void main(String args[]){
int num_employee=500; /* state….
String Course=”Intellipaat”; … state */
show(num_employee, Course);
}
}

Output:
Intellipaat 500
Class:A class is a user-defined entity that contain the state, behaviour, and identity of an object.
A class may have:

  • Modifiers
  • Class name
  • Blocks
  • variables
  • Java Methods
  • Constructors
  • Interface
class {
    Variables;
    Methods();
}

Watch this Java video by Intellipaat:

Blocks

Instance Blocks

  • Those blocks which are declared without using the static keyword are called instance blocks.
  • Instance blocks are executed as number of times as the class is loaded or object is created.

Static Block

  • Those blocks which are declared using static keyword are called static blocks.
  • Static Blocks are loaded only once when the class loads. It will not be executed again when the same class is loaded.
  • Static Block is executed first when the class loads, after that instance block is executed.

Example:

class Test{
{ // instance block
System.out,println(“Instance Block”);
}
static{ // static block
System.out,println(“Static Block”);
}
}
class Intellipaat{
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
}
}

Output:
Static Block
Instance Block
Instance Block

Certification in Bigdata Analytics

Object Creation

There are many ways to create an object:

  • Using new operator
  • Using clone() method
  • Using deserialization
  • Using newInstance()

In the above code, Object is created two times.

  • During the first object creation, JVM checks whether Test class is loaded or not. If not loaded, then it will load the class and the static blocks will be executed and instance and static variables will get the memory.
  • During the second object creation, JVM checks whether the class is loaded or not. As Test class has already loaded, so it will not execute the static block but instance block will be executed and instance variables will get the memory.
  • Just after the instance block constructors will be executed depending upon the constructors called.
  • Example:

Test t=new Test();
Here, default constructor will be executed. If the default constructor is not present, JVM will automatically put an empty default constructor Test(){}.

Know the major differences between today’s most prominent languages in the IT industry, check out this Java vs Python blog!

Java Constructors

  • Java Constructors are used to initialize object’s variables.
  • Constructors are called during the object creation.

There are certain rules for constructors:

  • Constructors name must be same as that of the class.
  • Constructors must not return any value, i.e. no return type
  • Constructors can contain both variables and methods.

There is always a default constructor in a class even if it is not declared by the user. JVM will automatically provide an empty default constructor.
There are two types of Constructors:

  • Default Constructor
  • Parameterized Constructor

Default Constructor:

Constructors with no arguments are called as default constructors.

// Default Constructor
class Intellipaat{
int a;
{ // instance block
System.out.println(“Instance Block”);
}
static{ // static block
System.out.println(“Static Block”);
}
Intellipaat(){ //default constructor
a=0;
System.out.println(“Default-Cons”);
}
public static void main(String args[]){
Intellipaat ob1=new Intellipaat(); // Intellipaat() after new represents default const.
Intellipaat ob2=new Intellipaat();
}
}

Output:
Static Block
Instance Block
Default-Cons
Instance Block
Default-Cons

Learn how to use the Super Keyword in Java to access the methods and variables of the parent class!

Parameterized Constructor:

Constructors with arguments are called parameterized constructers. There can be two argument constructor, three argument constructor, etc.

// Parameterized Constructor
class Intellipaat{
Intellipaat(){ //Default Constructor
System.out.println(“Default-Cons”);
}
Intellipaat(int b){ //1-Argument constructor
a=b;
System.out.println(“1-Arg-Cons”);
System.out.println(“Value Initialized:”+a);
}
Intellipaat(int b, String s){ //2-Argument constructor
a=b;
System.out.println(“2-Arg-Cons”);
System.out.println(“Value Initialized:”+” ”+s+” ”+and+” ”+a);
}
public static void main(String args[]){
Intellipaat ob1=new Intellipaat(); // Intellipaat() after new represents default const.
Intellipaat ob2=new Intellipaat(10); //1-Arg Cons
Intellipaat ob2=new Intellipaat(10, “Intellipaat”); //2-Arg Cons
}
}

Output:
Default-Cons
1-Arg-Cons
Value Initialized:10
2-Arg-Cons
Value Initialized: Intellipaat and 10

Become a Big Data Architect

this keyword

In the previous topic constructors, while object creating, only default constructors are called. To call parameterized constructors from default constructors this keywords are used.

  • this is a keyword that is use to access current class objects.
  • this contains current class reference.
  • You can pass arguments in this() method to call parameterized constructors.
// this keyword for variables
class Intellipaat{
int a=10; // instance variables
int b=20;
Intellipaat(int a, int b){ //here a and b are local variables
System.out.println(“2-Arg-Cons”);
System.out.println(a);
System.out.println(b);
System.out.println(this.a); //this has current class reference
System.out.println(this.b);
}
public static void main(String args[]){
Intellipaat ob=new Intellipaat(1,2);
}
}

Output:
2-Arg-Cons
1
2
10
20
In the above program, this is used to access current class objects.
Similarly, this can be used to call methods and constructors.

// this keyword for contructors
class Intellipaat{
int a=10;
int b=20;
Intellipaat(){
this(7,8,9); // calling 3-Arg Constructor
System.out.println(“Default-Cons”);
}
Intellipaat(int a, int b){
this(); //calling default constructor
System.out.println(“2-Arg Cons”);
}
Intellipaat(int a, int b, int c){ //3-Arg Constructor
System.out.println(“3-Arg Cons”);
}
public static void main(String args[]){
Intellipaat ob=new Intellipaat(1,2);
}
}

Output:
3-Arg Cons
Default Cons
2-Arg Cons

// this keyword for methods
public class Intellipaat{
int a=10;
int b=20;
void a(){
System.out.println(“Method a()”);
}
Intellipaat(int a, int b){
this(); //calling default constructor
System.out.println(“2-Arg Cons”);
}
public static void main(String args[]){
Intellipaat ob=new Intellipaat(1,2);
this.a();
}
}

Output:
2-Arg-Cons
Method a()

Still have queries? Come to Intellipaat’s Java Community, clarify all your doubts, and excel in your career!

Inheritance

Till now, you are writing separate program to perform different actions. But, sometimes, it is possible that you might want the code written in the previous program. To solve, this problem concept of inheritance was introduced. Inheritance is an important property of OOPs.

  • Inheritance is inheriting the existing class property, i.e. methods and variables into other class.
  • extends keyword is used to inherit a class.
  • Super and Sub classes: The class that inherits the property of other class is called a sub-class whereas the class whose property is inherited is called a super class.
  • Sub-class is called derived class, child class, or extended class.
  • Super class is also called parent class or base class.
  • Inheritance is used for code re-usability.

Aggregation: It represents HAS-A relationship. Aggregation means a class have an entity reference. It is used because it provides code re-usability. Inheritance is also used for code re-usability but you should use inheritance when if the relationship IS-A is continued throughout the lifetime of the objects involved otherwise use aggregation.
Example:
aggregation

Output:
Square is:4.0
Cube is:8.0

Composition:It is also a HAS-A relationship in java classes. Java composition is archived by using instance variables that refers to other object.
Example:
Output:

class Company{
private String firstname;
public void setFirstname(String firstname){
this.firstname=firstname;
}
public void getFirstname(){
System.out.println("Company name is: "+firstname);
}
}
public class CompanyDetails{
Company cmp;
public CompanyDetails(){
cmp=new Company();
cmp.setFirstname("Intellipaat");
}
public void getCmpName(){
cmp.getFirstname();
}
public static void main(String[] arg){
CompanyDetails cd=new CompanyDetails();
cd.getCmpName();
}
}

Output:
Company name is: Intellipaat
 There are five types of Inheritance:

  • Single Inheritance
  • Multi-Level Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance
  • Hybrid Inheritance

Single Inheritance

single inheritance

In single inheritance, a single subclass inherits the property of a super class.
Example:
In the above picture, class B inherits the property of parent class A.

public classInheritanceSingle{ //parent class
int a=10;
public void show(){
System.out.println(a);
}
public class Intellipaat extends InheritanceSingle{ //sub-class
public static void main(String args[]){
show();
System.out.println(a+10);
}
}

Output:
10
20

Multi-Level Inheritance

multilevel inheritance
In multi-level inheritance, a sub-class inherits a base class and that sub class becomes the base class for the third sub-class.
In the above picture

  • Class A: class A is the direct super class of class B and indirect super class of class C.
  • Class B: class B is the direct derived class of class A and the direct super class of class C.
  • Class C: class C is the direct derived class of class B and indirect derived class of class A. Class A is the indirect super class of class C.
public class A{
// statements
}
public class B extends A{
// statements
}
public class C extends B{
//statements
}

Hierarchical Inheritance

heirarchical
In hierarchical Inheritance, one direct super class is inherited by two or more than two derived classes.
In the above picture,

  • Class A is the direct super class of class B, C and D.
  • Class B, C and D are the direct sub-classes of class A.
public class A{
// statements
}
public class B extends A{
//statements
}
public class C extends A{
// statements
}
public class D extends A{
// statements
}

Multiple Inheritance

multiple
In multiple inheritance, one direct sub-class inherits two or more than two direct super classes.
In the above picture,

  • Class C is the direct sub-class of the class A and class B
  • Class A and B are the direct super classes of class C.
public class A{
// statements
}
public class B{
// statements
}
public class C extends A, B{
// statements
}

Note:

  • In Java, multiple Inheritance is not allowed.
  • Reason: It is possible that two or more than two direct super classes may have methods or variables that are similar. In that case, JVM will not identify which super class methods/variables has been called and will through an error.
public class A{
int a=10;
}
public class B{
int a=10;
}
public class C extends A, B{
public static void main(String args[]){
System.out.print(a); // error
}

In the above program, it is not clear whether class A’s variable has been called or class B’s variable a has been called. In that case, JVM will throw an error.
To solve this problem, concept of Interface was introduced. In Java, multiple interface is allowed but multiple inheritance is not allowed.

Hybrid Inheritance

hybrid
Hybrid Inheritance is the combination of two or more than two types of inheritance.
Like multiple inheritance, hybrid inheritance is also not allowed in java because of the same problem.

public class A{
// statements
}
public class B extends A{
// statements
}
public class C extends A{
// statements
}
public class D extends B, C{
// statements
}

In the above picture,

  • Class A, B and C make hierarchical inheritance.
  • Class B, C and D make multiple inheritance.
  • The combination of the two inheritances are known as hybrid inheritance.

Note:

  • A sub-class can’t inherit constructors as they are not the part of members of a class.
  • A sub-class can’t inherit private members of a super class.
  • There is always an indirect super class for all the classes(even if there is only one class), i.e. Object class. JVM automatically extends Object class in the topmost class. It is available in java.lang package.

super keyword

In the above topic inheritance, if you want to call super class members, super keywords are used.

  • The super keyword is used to access parent or super class objects. Reference super contains the reference of the super class object.
  • super keyword can be used for methods, contructors and variables.
  • You can pass arguments in super() method to call parameter constructors of super class.
// super keyword for variables
public class Intellipaat{ // parent class or super class
int a=10; // instance variable
}
public class B extends Intellipaat{ // sub-class
public static void main(String args[]){
System.out.println(super.a);
System.out.println(a);
}
}

Output:
10
10
In the above program, value of a can be printed either directly or using super keyword. Variable a belongs to super class Intellipaat.
Note:

  • Call to super must be the first statement in the sub-class constructor.
  • Call to this must be the first statement in the current class constructor.
// super keyword for constructors
public class Intellipaat{ // parent class or super class
int a=10;
Intellipaat(){
this(10);
System.out.println(“Super-Def-Cons”);
}
Intellipaat(int a){
System.out.println(“Super 1-Arg Cons”);
}
}
public class B extends Intellipaat{ // sub-class
B(){
super();
System.out.println(“Sub-Def-Cons”);
}
public static void main(String args[]){
B b=new B();
}
}

Output:
Super 1-Arg Cons
Super-Def-Cons
Sub-Def-Cons
In the above program,

  • In sub-class default constructor, if the super() keyword to call default constructor of super class is not present, then JVM automatically provides super() in sub class default constructor.
// super keyword for method
public class Intellipaat{ // parent class or super class
int a=10;
Intellipaat(){
System.out.println(“Super-Def-Cons”);
}
Public void show(){
System.out.println(“Super show()”);
}
}
public class B extends Intellipaat{ // sub-class
B(){
System.out.println(“Sub-Def-Cons”);
}
public static void main(String args[]){
B b=new B();
super.show();
}
}

Output:
Super-Def-Cons
Sub-Def-Cons
Super show()

Want to know why majority of Java Developers are moving towards Hadoop? Get to know in this Reasons You Should Switch Career From Java to Hadoop blog!

Abstraction

The process of hiding the implementations and showing the functionality is called abstraction.
Let’s assume a case of cell phone. When user buys a phone, he doesn’t see how that phone had developed but sees only the working of phone such as calling, music, videos, etc. while inner implementations of cell phone remains hidden. This is called abstraction.
There are two ways to achieve abstraction:

  • Abstract class
  • Interface

Abstract class

  • Abstract class is used when you currently don’t know the implementation of a class or method, i.e. hidden part that user can’t see.
  • abstract keyword is used to make abstract class.
  • If a method is abstract, then the class having abstract method must also be abstract. But if a class is abstract, then it is not compulsory that it contains only abstract methods.
  • You cannot create objects for abstract classes.
  • Abstract class can contain constructors, static methods and final methods.
abstract class Intellipaat{
abstract void accountDetails();
void show(){}a
}

Interface

  • interface is a keyword which is used to define user defined data types.
  • Interface is special class which is fully abstracted.
  • Interface can be used to achieve the multiple inheritance in java.
  • One interface can extend one or more interfaces and one class can implement one or more interfaces.

Syntax:

<modifiers>interface <interfaceName>
{ 
//members
}
  • Interface can contain public final static variables, public abstract methods, public static inner classes.
  • Variables declared in the interface are by default public, final and static. So, it is unnecessary to use these modifiers for variables.
  • Methods declared in the interface are by default public and abstract. So, it is unnecessary to use these modifiers for methods.
interface inter1{
int a=22;
void show();
}
public class TestInterface implements inter1{
public void show()
System.out.println(“Intellipaat”);
}
public static void main(String args[]){
TestInterfacei=new TestInterface ();
i.show();
System.out.println(a);
}
}

Output:
Intellipaat
22
New features to interface from JDK 8:

  • You can now add default implementations to methods.

Suppose you have not implemented the method of the previous class and you make a call to that method, in that case JVM will show compile time error. Now from JDK 8, you can write a default implementation to that method in the interface.

interface inter1{
int a=22;
default void show()
System.out.println(“Intellipaat”);
}
}
public class TestInterface implements inter1{
public static void main(String args[]){
TestInterfacei=new TestInterface ();
i.show();
System.out.println(a);
}
}

Output:
Intellipaat
22

  • You can now define static methods in interface and can call them without creating object.
interface inter1{
int a=22;
static void show()
System.out.println(“Intellipaat”);
}
}
public class TestInterface implements inter1{
public static void main(String args[]){
inter1.show();
System.out.println(a);
}
}

Output:
Intellipaat
22
Why Interface?
In the topic multiple inheritance, we have seen some problems. To solve those interface topic has been introduced.

interface inter1{
int a=20;
}
interface inter2{
int a=30;
}
public class TestInterface implements inter1{
public static void main(String args[]){
System.out.println(inter1.a); // print 20
System.out.println(inter2.a); //print 30
}
}

Suppose you have implemented both the show() methods and you make a call to those two methods, because by default variables are static so, you can use class/interface name to call those variables. Here, the problem of ambiguity gets solved.

  • Interface doesn’t contain constructors.
  • Super keyword cannot be used for interface.

Certification in Bigdata Analytics

Polymorphism

  • Polymorphism is one name-many forms.
  • Polymorphism is the ability of an object to behave differently at different situations.

Example:

  • Power button has a polymorphic behaviour.
  • When you press once, it will switch on the device.
  • When you press it again, device will be switched off.
  • Plus + operator has a polymorphic behaviour.
  • When operands are numeric then it will perform arithmetic addition.
  • When the operands are of String type, then it will perform String Concatenation.

Types of Polymorphism:

  • Static polymorphism
  • Dynamic Polymorphism

Static Polymorphism/Compile Time Polymorphism/Early Binding

  • Static Polymorphism can be achieved using method overloading.
  • It can be achieved with both instance and static methods.
  • Static polymorphism is also called as compile time polymorphism or early binding because java compiler is responsible to bind the method calls with actual method at compile time.
  • Java compiler will verify the method name first then method parameters to verify the matching method.
  • Return type will not be considered to achieve static polymorphism.

Dynamic Polymorphism/Run time Polymorphism/Late Binding

  • Dynamic Polymorphism can be achieved using both method overriding or dynamic dispatch.
  • It is also called as run time polymorphism or late binding because JVM is responsible to decide which method will be invoked based on actual object available in reference variable.
  • It can be achieved only with instance method and can’t be achieved using static method.

Dynamic Dispatch

  • The process of assigning subclass object to super class reference variable is called as dynamic dispatch.
class A{}
class B extends A{}
class C extends A{}
class D extends B{}
class E extends B{}

Which of the following are valid?

A ob=new A();   //valid
A ob=new B();   //valid
A ob=new C();   //valid
B ob=new B();   //valid
B ob=new D();  //valid
B ob=new E();  //valid
C ob=new A();   //valid
B ob=new A(); // invalid
D ob=new A(); //invalid
B ob=new C(); // invalid

Learn about the most trending technology for Big Data, in this very informative tutorial blog on Java Mapreduce!

Method Overloading

  • You can write multiple methods inside the class with the same name by changing parameters. This process is called as method overloading.
  • When you are overloading methods then
    • Method name must be same
    • Method parameter must be changed in terms of number of parameters, type of parameters and order of parameters.
    • Method return type can be anything.

Why method overloading?
Method overloading helps in code re-usability.
Suppose you want to perform addition in java and if overloading was not possible, then you would have wrote addition methods as number of times as you want to perform addition.

class Intellipaat{
void add(int a, int b){
System.out.println(a+b);
}
void add(float a, float b){
System.out.println(a+b);
}
}
class OverLoadTest{
public static void main(String args[]){
Intellipaat ob=new Intellipaat ();
ob.add(10,20);
ob.add(20.5,20.5);
}
}

Output:
30
41
Ambiguity Error in overloading

class Intellipaat{
void add(long a, int b){
System.out.println(a+b);
}
void add(int a, long b){
System.out.println(a+b);
}
}
}
class OverLoadTest{
public static void main(String args[]){
Intellipaat ob=new Intellipaat ();
ob.add(10,20);
ob.add(1000,100);
}

In the above program, JVM will not be able to decide which method to choose to pass the parameters as int is compatible to long(for details refer type casting topic).
In that case, it will show an ambiguity error.
Overloading of main method

class OverLoadTest{
public static void main(String args[]){
System.out.println(“String args[] main()”);
OverLoadTest.main(Intellipaat);
}
public static void main(String args){
System.out.println(“String argsmain():”+” ”+args);
}
public static void main(String args1, String args2){
System.out.println(“String two argsmain():”+” ”+args1+” “+args2);
}
}

It will only call the main method with String[](String array) as an argument. But we can call the main method explicitly.
Output:
String args[] main()
String argsmain(): Intellipaat

Method Overriding

  • Method overriding is a process of implementing super class methods in sub class with the same signature.
class Intellipaat{
void show(){
System.out.println(“Super Intellipaat”);
}
}
class OverLoadTest extends Intellipaat{
void show(){
System.out.println(“Sub Intellipaat”);
}
public static void main(String args[]){
Intellipaat ob=new Intellipaat();
ob.show();
Intellipaat ob1=new OverLoadTest (); // overridden method will be called
ob1.show();
}
}

Output:
Super Intellipaat
Sub Intellipaat
Why to override the method?

  • According to Object Oriented best practices, “Classes are closed for modification”, i.e. if you want to modify the functionality of existence class then you should not disturb the existing class.
  • It is always better to write a sub class and provide the required implementations in sub class.
  • Sub class can be used to add new functionality, to modify existing functionality and to inherit existing functionality.

Rules to override the method:

  • Sub class method name must be same as super class method name.
  • Sub class method parameters(in terms of type, numbers and order) must be same as super class method parameters.
  • Sub class return type name must be same as super class method return type.

Note:
If super class method return type is class type, then sub class return type cab be either super class or sub class itself as return type.

class Hey{
A method1(){}
}
class Intellipaat extends Hey{
A method1(){}
B method1(){} //valid from Java 5
C method1(){} //invalid
}
class A{}
class B extends A{}
class C{}
  • Sub class access modifier must be either same or higher than the super class modifier.

Super Class

Sub Class

public

public

protected

protected, public

default

default, protected, public

private

private, default, protected, public

  • When super class method is instance method then you have to override in sub class as instance only.
  • Final methods cannot be overridden.
class Intellipaat{
final void show(){ // cannot override
System.out.println(“Super Intellipaat”);
}
}
class OverLoadTest extends Intellipaat{
void show(){ // produce error
System.out.println(“Sub Intellipaat”);
}
//compile time error
  • Static methods cannot be overridden.

Overridden static method will be hided. This is also called as method hiding.

class Intellipaat{
static void show(){
System.out.println(“Super Intellipaat”);
}
}
class OverLoadTest extends Intellipaat{
static void show(){ // hide
System.out.println(“Sub Intellipaat”);
}
public static void main(String args[]){
Intellipaat ob=new OverLoadTest();
ob.show(); /* should call the sub class overridden method but that goes hidden and parent class method is called */
}
}

Output:
Super Intellipaat

  • Private methods cannot be overridden.

Encapsulation

encapsulation

class person{
int age; // state or data members or fields or properties
String name;
Walk();
Eat(); // behaviour or member function functions or methods
}

Access Modifiers

  • Access modifiers can be used to specify the scope or visibility of the class or members of the class.
  • There are three types of access modifiers:
    • private
    • protected
    • public
  • There are four scopes available:
    • Private scope
    • Protected scope
    • Default scope
    • Public scope
Private Scope
  • When you are using private modifiers with the members of the class then the scope of those members will be private scope.
  • Private scope is also called as class scope, i.e. private members must be accessed from the same class where it is declared.
  • Private members cannot be accessed from the outside class, not even from the sub class, i.e. private members cannot be inherited to sub class.
  • Private modifiers can only be used with the members of the and not for the class itself.
package p1;class PrivateTest{
private void show()
{
System.out.println("Intellipaat”);
}
}class Intellipaat{
public static void main(String args[]){PrivateTestob = new PrivateTest ();
ob.show(); // private access, must be accessed in the same class
}
}

Output:
error: show() has a private access in A

Default Scope
  • When you are not using any modifiers with the members of the class then the scope of those members will be default scope.
  • Default scope is called the packaged scope, i.e. default members can be accessed from the same class, sub class and non-sub class which are available in the same package.
  • Default members cannot be accessed from the outside package, i.e. default members will not be inherited to sub class available in the outside package.
  • Default scope is available for both the classes and their members.
package p1;class DefaultTest{
void show()
{
System.out.println("Intellipaat”);
}
}
package p2;
import p1.*;class Intellipaat{
public static void main(String args[]){DefaultTestob = new DefaultTest ();
ob.show(); // package is diiferent}
}

Output:
Compilation error

Protected Scope
  • When you are using protected modifiers with the members of the class then the scope of those members will be protected scope.
  • Protected members can be accessed from the same class, sub class and non-sub class which are available in the same package.
  • Protected members can be accessed from the sub classes which are available in the different package.
  • Protected members cannot be accessed from the non-sub classes which are available in different packages.
  • Protected members can only be used with the members of the and not for the class itself.
package p1;
public class ProtectedTest {
protected void show() {
System.out.println("Intellipaat");
}
}package p2;
import p1.*; //import all classes from p1 packageclass Intellipaat extends ProtectedTest{ //sub class can access protected members
public static void main(String args[]) {ProtectedTestobj = new ProtectedTest ();
obj.show();
}}

Output:
Intellipaat

Public Scope
  • When you are using public modifiers with the members of the class then the scope of those members will be public scope.
  • Public members can be accessed from anywhere.
  • Public modifiers can be used for both classes and their members.

Example:

package p1;public class PrivateTest {
public void show() {
System.out.println("Intellipaat");
}
}
package p2;
import p1.*;
class Intellipaat extends PrivateTest{
public static void main(String args[]) {
PrivateTestobj = new PrivateTest ();
obj.show();
}
}

Output:
Intellipaat

Go for the most trending and the professional Big Data Hadoop Certification Training for a stellar career now!

Package

  • A package is a namespace that organizes a set of related classes, interfaces, enums and annotations.
  • Package indicates the directory or folder in your file system where you can place your project files.
  • Package can be defined as namespace to identify the classes uniquely.
  • Package can be used to specify the access scope of your class or class members.

Syntax:  package <packageName>;
Example:
package p1;
package p2;

package p1; //p1 is the package namepublic class PackageTest {
public static void main(String args[]) {public void show() {
System.out.println("Intellipaat");}
}
}

Rules to compile and run package classes;

Compile: javac -d .java
Run: java .

To compile and run the above code:

javac -d . PackageTest.java
java p1.PackageTest

Output:
Intellipaat

• When you are writing classes without any package declaration statement, then those classes will be placed in the default package.
• Default package is the package without any name, i.e. when you compile source files with default package, then compiled class files will be placed in current folder.
• When you are writing classes with a package declaration statement then those classes will be placed in the specified package, i.e. when you compile source files with package declaration statement then compiled class files will be placed in specified package.
• When a class is specified inside a package then that class must be referred always with the package name which is also called as fully qualified class name.
p1.PackageTest;
Organizing Package Names
• Package name is a combination of multiple words separated with dot(.) symbol. Each word in the package name represents one folder or directory in the file system.
Example:

package com.Intellipaat.org.developer;
package com.Intellipaat.org.research;
package com.Intellipaat.org.trainer;

Package

Program to understand packages:

package com.Intellipaat.p1;
class IntellipaatDevelop{
public static void main(String args[]){
System.out.println(“Intellipaat-Develop”);
}
}

 

package com.Intellipaat.p2;
class IntellipaatResearch{
public static void main(String args[]){
System.out.println(“Intellipaat-research”);
}
}

Package2
This is how packages are created and classes are stored inside the packages.
Note:

  • javac -d . IntellipaatResearch.java; Here, dot(.) symbol is used as location, so package will be created in the current working directory and compiled classes will be placed in that package.
  • If you want to create packages in the specified directory instead of current working directory, then you have to specify the location.

javac -d D:Intellipaatp1 IntellipaatResearch.java;
CLASSPATH

  • CLASSPATH represents the path where class files, packages or JAR files available.
  • By default, you can access the classes from the same location where it is available.

Example:
java com.Intellipaat.p1.IntellipaatDevelop;
This will give error if the class path is not set.

  • When you want to access classes from other location of file system then you need to specify the location of class file by setting the CLASSPATH.

Package2

  • Temporarily for current Execution:

java -cp D:package com.Intellipaat.IntellipaatResearch;-> runs successfully

  • Temporarily for current Command Prompt:

set CLASSPATH=%CLASSPATH%; D:package;
java com.Intellipaat.IntellipaatDevelop;   -> runs successfully

  • Permanently set:
    • Go to my computer properties
    • Click on Advanced system settings
    • Click on Environment Variable Button
    • Click on New Button in the user variable
    • Provide the required class info

Variable Name- CLASSPATH

Variable value- %CLASSPATH%; D:package;

  • Click on OK button in all windows.

Interested in learning Java? Enrol in our Java online course now!

Importing Packages

  • If you want to access one class from another class with in the same package then you can access directly without using any package name.
  • If you want to access a class from a different package, then that class must be public, that package must be available in the classpath, and that package information must be specified.

Example:

package p1;
public class Intellipaat{}
package p2;
import p1.*; // this will import all classes from p1 package
public class ImportTest extends Intellipaat{}

• Import statement allows you to access classes from other packages.
Static Import
• You can access the classes of other packages by using normal statements whereas you can access public static members of the class by using static import statements.
Example:

package p1;public class StaticTest {
static void show() {
System.out.println("Intellipaat");
}
}
package p2;
import static p1.*;
class Intellipaat extends PrivateTest{
public static void main(String args[]) {
show();
}
}

Output:
Intellipaat

  • Through static import you can call static methods or variables of other package classes directly, i.e. without creating object.

Conclusion

This brings us to the end of Java tutorial. In this tutorial, we learned in detail about the overview of Java.

We also covered almost all the main parts of Java. If you want to learn more, I would suggest trying our Intellipaat “Java” course that covers in-depth knowledge of most of the important topics like Basics of Java, Array, Exception Handling, Multi-threading, packages, OOPs, etc. to make you a good Java programmer.

Join the Intellipaat Java training course and Certification today and let your career boom towards the domain of Software Developer.

Course Schedule

Name Date Details
Python Course 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 04 May 2024(Sat-Sun) Weekend Batch
View Details
Python Course 11 May 2024(Sat-Sun) Weekend Batch
View Details

Full-Stack-ad.jpg