CSE1007 - Java Programming: Module 2: Object Oriented Programming

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 136

CSE1007 – Java Programming

Module 2: Object Oriented Programming


Handled by
Dr. A. Balasundaram
Assistant Professor (Sr. Grade 1)
School of Computer Science and Engineering (SCOPE)
Centre for Cyber Physical Systems (CCPS)
Vellore Institute of Technology, Chennai
Contents

Text Book
Herbert Schildt, The Complete Reference -Java, Tata McGraw-Hill Education, Tenth Edition, 2017.
Contents
 Java Classes and Objects
 Java Attributes and Methods
 Java Constructors and Modifiers
 static and this keyword
 Java Abstraction (Abstract Classes and Interfaces)
 Java Encapsulation
 Java Inheritance and Polymorphism
 Java Packages
Object Oriented Programming (OOP)
 OOP stands for Object-Oriented Programming.
 Procedural programming is about writing procedures or methods that perform operations on
the data, while object-oriented programming is about creating objects that contain both data
and methods.
 Object-oriented programming has several advantages over procedural programming:
 OOP is faster and easier to execute.
 OOP provides a clear structure for the programs.
 OOP helps to keep the Java code DRY "Don’t Repeat Yourself", and makes the code easier to maintain,
modify and debug.
 OOP makes it possible to create full reusable applications with less code and shorter development time.
 The "Don’t Repeat Yourself" (DRY) principle is about reducing the repetition of code
Java Classes & Objects
 Classes and Objects are the two main aspects of OOP.
 Classes is a template for Objects , and an Object is an instance of a Class.
 When the individual Objects are created, they inherit all the variables and methods from the Class.
Java Classes
 A Class is like an object constructor, or a "blueprint" for creating objects.
 Java is an object-oriented programming language.
 Everything in Java is associated with classes and objects, along with its attributes and methods.
 For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such
as drive and brake.
 Create a Class : (Syntax)
public class Dog {
String breed, color; // Member Data
int age;
void barking() { } // Member Methods
void hungry() { }
void sleeping() { }
}
Java Objects
 In Java, an object is created for a class.
 We have already created the class named Dog, so now we can create objects (Dog1, Dog2, Dog3 So on....) for
the class Dog.
 Using objects we can access the member variables (attributes / fields) and methods.
Java Objects
public class Dog {
String breed, color // Member Data/Attributes
int age;
void barking() { } // Member Methods
void hungry() { }
void sleeping() { }
public static void main(String[] args) {
Dog Dog1 = new Dog(); // Dog1 object is Created
System.out.println(Dog1.breed);
System.out.println(Dog1.color);
Dog Dog2 = new Dog(); // Dog2 object is Created
System.out.println(Dog2.breed);
System.out.println(Dog2.color);
}
}
Accessing or Modify Attributes/Methods
 Can access attributes by creating an object of the class, and by using the dot
operator (.)
 Another term for class attributes is fields.
public class Main {
int x;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 40; // Modifying
System.out.println(myObj.x); // Accessing
}
}
Example: Java Classes and Objects
// Class Declaration
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed, int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
Example: Java Classes and Objects
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
Example: Java Classes and Objects
// method 4
public String getColor()
{
return color;
}
@Override
public String toString()
{
return("Hi my name is "+ this.getName()+ ".\nMy breed,age and color are " + this.getBreed()+"," + this.getAge()+ ","+
this.getColor());
}
public static void main(String[] args)
{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Java Constructors
 In Java, a constructor is a block of codes similar to the method.
 It is called when an instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is called.
 Rules for creating constructor :
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized.
 Constructor Types :
 Default Constructor
 Parameterized Constructor
Default Constructor
 A constructor is called "Default Constructor" when it doesn’t have any parameter.
 Rule: If there is no constructor in a class, then compiler automatically creates a default constructor.
 Syntax :
<class_name>(){}
 Example :
class Bike1{
//creating a default constructor
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Example - Default Constructor
 It used to provide the default values to the object like 0, null, etc.,.
//Default constructor which displays the default values
class Student{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display(); O/P:
} 0 null
0 null
}
Parameterized Constructor
 A constructor which has a specific number of parameters.
 It is used to provide different values to distinct objects.
class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n){ id = i; name = n; }
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1=new Student(12345, “Bala");
Student s2=new Student(65432, “Sundaram");
//displaying values of the object
s1.display(); s2.display(); O/P:
12345 Bala
}
65432 Sundaram
}
Example - Default Constructors
// Create a Main class
public class Main {
// Create a class attribute
int x;
// Create a class constructor for the Main class
public Main() {
// Set the initial value for the class attribute x
x = 5;
}
public static void main(String[] args) {
// Create an object of class Main
//(This will call the constructor)
Main myObj = new Main();
// Print the value of x
System.out.println(myObj.x);
}
}
Example - Parameterized Constructors
// Example of Parameterized Constructor
public class Main {
int modelYear;
String modelName;
public Main(int year, String name) {
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(2019, “Alto K10");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
// Outputs : 2019 Alto K10
Method Overloading
 Multiple methods in a class, can have the same name with different parameters.
 To perform only one operation, having same name of the methods increases the readability
of the program.
 For Example : To perform addition of the given numbers but there can be any number of
arguments, if you write the method such as func1(int,int) for two parameters, and
func2(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
 Advantage : Increases the readability of the program.
 Ways to Overload :
 By changing number of arguments
 By changing the data type

Note: Method Overloading isn’t possible by changing the method return type only.
Example: Method Overloading
class Adder{
// 2 Arguments of Integer Data type
static int add(int a, int b){return a+b;}
// 3 Argument of Interger Data type
static int add(int a, int b, int c){return a+b+c;}
// 2 Argument of Double Data type
// Output : 22, 36, 24.9
static double add(double a, double b){return a+b;}
}
class TestOverloading{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,12,13))
System.out.println(Adder.add(12.3,12.6));
}
}
Example: Method Overloading
 Can we overload java main() method?
 Answer : Yes, We can overload the main method in java but JVM only calls the original main method, it will never call
our overloaded main method.
public class TestOverloading1{
public static void main(int args)
{ System.out.println("main() overloaded" + " method 1 Executing"); }
public static void main(char args)
{ System.out.println("main() overloaded" + " method 2 Executing"); }
public static void main(Double[] args)
// Output : Original main() executing
{ System.out.println("main() overloaded" + " method 3 Executing"); }
// Original main()
public static void main(String[] args)
{ System.out.println("Original main()" + " Executing"); }
}
Method Overloading and Type Promotion
Example: Method Overloading
//Example of Method Overloading with TypePromotion
class OverloadingCalculation{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation obj=new OverloadingCalculation();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Example: Method Overloading
//Example of Method Overloading with Type Promotion if matching found
class OverloadingCalculation{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
public static void main(String args[]){
OverloadingCalculation obj=new OverloadingCalculation();
obj.sum(20,20); //now int arg sum() method gets invoked
}
}
Examples: Method Overloading
Ambiguity : If there are no matching type arguments in the method, and each method
promotes similar number of arguments, there will be ambiguity.
//Example of Method Overloading with Type Promotion in case of ambiguity
class OverloadingCalculation{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
public static void main(String args[]){
OverloadingCalculation obj=new OverloadingCalculation();
obj.sum(20,20);//now ambiguity
}
}
// Output:Compile Time Error
Constructor Overloading
 In Java, a constructor is just like a method but without return type.
 It can also be overloaded like Java methods.
 It is a technique of having more than one constructor with different parameter lists.
 They are arranged in a way that each constructor performs a different task.
 They are differentiated by the compiler by the number of parameters in the list and their
types.
class Student{ Examples: Constructor Overloading
int id, age;
String name;
Student(int i,String n){ // creating two arg constructor
id = i; name = n;
}
Student(int i,String n,int a){ //creating three arg constructor
id = i; name = n; age=a;
} /* Output : 300, Balasundaram
301, Rahul, 25 */
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(300,“Balasundaram");
Student s2 = new Student(301,“Rahul",25);
s1.display();
s2.display();
}}
Examples: Constructor Overloading
// Java program to illustrate Constructor Overloading
class Box {
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
// constructor used when no dimensions specified
Box() {
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
} }
// Driver code Examples: Constructor Overloading
public class Test {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
} }
Differences b/w Constructor and Methods in Java
Differences b/w Constructor and Methods in Java
Java Copy Constructor
 There is no copy constructor in Java. However, we can copy the values from one object to another like
copy constructor in C++.
 There are many ways to copy the values of one object into another in Java.
 By constructor
 By assigning the values of one object into another.
 By clone() method of Object class.
 Important Questions -
 Does constructor return any value? (Ans : Yes)
 Can constructor perform other tasks instead of initialization? (Ans : Yes)
 Is there Constructor class in Java? (Ans : Yes)
Example-1 - By constructor
//Java program to initialize the values from one object to another object.
class Student{
int id;
String name;
//constructor to initialize integer and string
Student(int i,String n){
id = i; name = n;
/* Output : 396, Bala
}
* 396, Bala*/
//constructor to initialize another object
Student(Student s){
id = s.id; name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(396,“Bala");
Student s2 = new Student(s1);
s1.display();
s2.display();
}}
Example-1 - By Assigning
//Java program to assign the values from one object to another object.
class Student{
int id;
String name;
Student(int i,String n){
id = i; name = n; /* Output : 396, Bala
} * 396, Bala*/
Student(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(396,“Bala");
Student s2 = new Student();
s2.id=s1.id; s2.name=s1.name;
s1.display(); s2.display();
}
}
Java Static Keyword
 Used for memory management mainly.
 The static keyword belongs to the class than an instance of the class.
 static can be used for a:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
 Nested class
Java Static Variable
 Any variable, declared as static, known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is not unique for each object).
 For Eg:- the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.
 Advantages :- It makes your program memory efficient (i.e., it saves memory).
 Java static property is shared to all objects.
Understanding the problem without static variable:
class Student{
int rollno; String name;
String college = "VIT";
}
 Suppose there are 500 students in my college, now all instance data members will get memory each time when the
object is created. All students have its unique rollno and name, so instance data member is good in such case. Here,
"college" refers to the common property of all objects. If we make it static, this field will get the memory only once.
Java Static Variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno; //instance variable
String name;
static String college ="VIT"; //static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(396,"Deepu");
Student s2 = new Student(397,"Swetha");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}}
Program of the counter without static variable
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.
class Counter{
//will get memory each time when the instance is created
int count=0;
Output:
Counter(){
count++; //incrementing value 111
System.out.println(count);
}
public static void main(String args[]){
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Program of the counter with static variable
//Java Program to illustrate the use of static variable which
//is shared with all objects.
class Counter{
//will get memory only once and retain its value
static int count=0;
Counter(){
Output:
//incrementing the value of static variable
count++; 123
System.out.println(count);
}
public static void main(String args[]){
//creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
 It belongs to the class rather than the object of a class. Java Static Method
 It can be invoked without the need for creating an instance of a class.
 It can acc//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "VIT";
//static method to change the value of static variable
static void change(){
college = “VIT University";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){ Java Static Method
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod{ Output:
public static void main(String args[]){ 111 Ram VIT University
222 Kumar VIT University
Student.change();//calling change method 333 Shiva VIT University
//creating objects
Student s1 = new Student(111,“Ram");
Student s2 = new Student(222,"Kumar");
Student s3 = new Student(333,“Shiva");
//calling display method
s1.display(); s2.display(); s3.display();
}
}
Java static Keyword - Restrictions
Restrictions for the static method
 The static method can not use non static data member or call non-static method directly.
 this and super cannot be used in static context.
class A{
int a=40; //non static
public static void main(String args[]){
System.out.println(a);
}
}
// Compilation Error
Java static block
 Used to initialize the static data member.
 It is executed before the main method at the time of classloading.
class A{
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
/* Output:
static block is invoked
Hello main */

Can we execute a program without main() method? –> No


Java this Keyword
 There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the
current object.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
Example Program (without this)
// Understanding the problem without this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno; name=name; fee=fee;
}
void display() { System.out.println(rollno+" "+name+" "+fee); }
} Output:
class TestThis1{ 0 null 0.0
public static void main(String args[]){ 0 null 0.0
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Example Program (with this)
// Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno; this.name=name;
this.fee=fee;
}
void display() { System.out.println(rollno+" "+name+" "+fee); }
} Output:
class TestThis1{ 111 ankit 5000
public static void main(String args[]){ 112 sumit 6000
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Example Program (does not require this)
// If local variables(formal arguments) and instance variables are different there is no need to use this keyword like in the following program:
class Student{
int rollno;
String name;
float fee;
Student(int r,String n, float f){
rollno=r;name=n; fee=f;
}
void display() { System.out.println(rollno+" "+name+" "+fee); }
}
class TestThis1{ Output:
public static void main(String args[]){ 111 ankit 5000
112 sumit 6000
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
this to invoke current class method
 To invoke the method of the current class by using the this keyword: If you don’t use the this keyword, compiler
automatically adds this keyword while invoking the method.
class A{
void m(){ System.out.println("hello m"); }
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
Output:
} hello n
hello m
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
this to invoke class Default Constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In
other words, it is used for constructor chaining.
// Default Constructor
class A{
A(){ System.out.println("hello a"); }
A(int x){
this();
System.out.println(x);
}
Output:
} hello a
10
class TestThis{
public static void main(String args[]){
A a=new A(10);
}
}
this to invoke class Parameterized Constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor.
// Parametrized Constructor
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){ System.out.println(x); }
} Output:
5
class TestThis6{
hello a
public static void main(String args[]){
A a=new A();
}
}
class Student{
Real usage of this() constructor call
int rollno; String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno; this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course); //reusing constructor
this.fee=fee;
}
void display(){ Output:
System.out.println(rollno+" "+name+" "+course+" "+fee); 111 ankit java null
} 112 sumit java 6000
}
class TestThis{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display(); s2.display();
}}
Real usage of this() constructor call
Rule: Call to this() must be the first statement in constructor.
class Student{
int rollno; String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno; this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this.fee=fee; this(rollno,name,course); //C.T.Error
}
void display(){
System.out.println(rollno+" "+name+" "+course+" "+fee); Output:
} Compile Time Error:
} Call to this must be first statement in constructor
class TestThis{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display(); s2.display();
}
}
this to be passed as an argument in the method
It can also be passed as an argument in the method. It is mainly used in the event handling.
class S2{
void m(S2 obj){
System.out.println(“Method is invoked");
}
void p(){
m(this);
} Output:
public static void main(String args[]){ Method is invoked

S2 s1 = new S2();
s1.p();
}
}
this to be passed as argument in the constructor call
It can pass as an argument in the constructor also. It is useful if we have to use one object in multiple
classes.
class B{
A4 obj;
B(A4 obj){ this.obj=obj; }
void display(){
System.out.println(obj.data); //using data member of A4 class
}
} Output:
class A4{ 10

int data=10;
A4(){ B b=new B(this); b.display(); }
public static void main(String args[]){
A4 a=new A4();
}}
this keyword can be used to return current class instance
We can return this keyword as an statement from the method. In such case, return type of the method must
be the class type (non-primitive)
class A{
A getA(){
return this;
}
void msg(){
System.out.println("Hello java");}
Output:
} Hello java
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Java Modifiers
 Modifiers are keywords used to change their meanings. Java has a wide variety of modifiers, including
the following:
 Access Modifiers : to set access levels for classes, variables, methods and constructors. The four access
levels are :
 default : Visible to the package
 private : Visible to the class only
 public : Visible to the world.
 protected : Visible to the package and all subclasses.
 Non Access Modifiers :
 static : used for creating class methods and variables.
 final : used for finalizing the implementations of classes, methods, variables.
 abstract : used for creating abstract classes and methods.
 synchronized and volatile modifiers, which are used for threads.
Java Modifiers
private Access Modifier
 The private access modifier is accessible only within the class.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
private Access Modifier
 The private access modifier is accessible only within the class.
public class Simple{
private int data=40;
private void msg(){System.out.println("Hello java");}
public static void main(String args[]){ Output:
40
Simple obj=new Simple(); Hello java
System.out.println(obj.data); //No Compile Time Error
obj.msg(); //No Compile Time Error
}
}
private Access Modifier
 Role of Private Constructor: If you make any class constructor private, you cannot create the instance of
that class from outside the class.
class A{
private A(){}//private constructor
void msg(){
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A(); //Compile Time Error
}
}
Default Access Modifier
 If you don’t use any modifier, it is treated as default by default.
 It is accessible only within package.
 It cannot be accessed from outside the package.
 It provides more accessibility than private. But, it is more restrictive than protected, and public.
//save as A.java
package pack;
class A{ void msg() { System.out.println("Hello"); } }
//save as B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
} }
The scope of class A and its method msg() is default so it cannot be accessed from outside the package.
protected Access Modifier
 Created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside
the package. But msg() of this package is declared as protected, so it can be accessed from outside the class only
through inheritance.
//save by A.java
package pack;
public class A{
Output:
protected void msg(){ System.out.println("Hello"); } Hello
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B(); obj.msg();
}
}
protected Access Modifier
 Created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside
the package. But msg() of this package is declared as protected, so it can be accessed from outside the class only
through inheritance.
//save by A.java
package pack;
public class A{
Output:
protected void msg(){ System.out.println("Hello"); } Hello
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B(); obj.msg();
}
}
public Access Modifier
 It is accessible everywhere. It has the widest scope among all other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){ System.out.println("Hello"); }
} Output:
Hello
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A(); obj.msg();
}
}
Java Abstraction
 It is the nature of dealing with ideas rather than events.
 For Example : Consider E-mail, complex details such as what happens as soon as you
send an e-mail, the protocol your e-mail server uses are hidden from the user.
 Therefore, to send an e-mail, just need to type the content, mention the address of the
receiver, and click send.
 In OOP : Abstraction is a process of hiding the implementation details from the user,
only the functionality will be provided to the user.
 In other words, User will have the information on what the object does instead of how
it does it.
 In Java, Abstraction is achieved using Abstract classes and Interfaces.
Abstract Class
 A class which contains the abstract keyword in its declaration is known as Abstract
class.
 Abstract classes may or may not contain abstract methods, i.e., methods without body
( public void get(); )
 But, if a class has at least one abstract method, then the class must be declared
abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
 The abstract keyword is a non-access modifier, used for classes and methods
Example-1: Abstract Class
/* File name : Employee.java */
public abstract class Employee {
private String name, address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name; this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
Example-1: Abstract Class
public void mailCheck() {
System.out.println("Mailing a check to " +
this.name + " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() { return name; }
public String getAddress() { return address; }
public void setAddress(String newAddress) { address = newAddress; }
public int getNumber() { return number; }
}
Example-1: Abstract Class
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String [] args) {
/* Following is not allowed and would raise error */
Employee e = new Employee(“Balasundaram A", "Chennai", 50);
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
/* Exception in thread "main" java.lang.Error: Unresolved
* compilation problem: Cannot instantiate the type Employee */
Example-2: Abstract Class and Methods
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}}
Example-2: Abstract Class and Methods
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Example-3: Abstract Class and Methods
abstract class EMPLOYEE {
private String Name;
private int Number;
public EMPLOYEE(String name, int number) {
System.out.println("Constructing an Employee");
this.Name = name;
this.Number = number;
}
public String getName() { return Name; }
public abstract double computePay(); // Remainder of class definition
}
class SAL extends EMPLOYEE {
private double salary; // Annual salary
public SAL(String name, int number, double newsalary) {
super(name, number);
salary = newsalary;
}
Example-3: Abstract Class and Methods
abstract class EMPLOYEE {
private String Name;
private int Number;
public EMPLOYEE(String name, int number) {
System.out.println("Constructing an Employee");
this.Name = name;
this.Number = number;
}
public String getName() { return Name; }
public abstract double computePay(); // Remainder of class definition
}
class SAL extends EMPLOYEE {
private double salary; // Annual salary
public SAL(String name, int number, double newsalary) {
super(name, number);
salary = newsalary;
}
Example-3: Abstract Class and Methods
public double computePay() {
System.out.print("The Salary for " + getName() + " is : " );
return salary+2000;
}
}
class Emp{
public static void main(String[] args){
SAL e = new SAL(“Balasundaram A", 3, 2000.0);
System.out.println(e.computePay());
}
}
/* Constructing an Employee
* The Salary for Balasundaram A is : 4000.0 */
Java Interfaces
 Another way to achieve abstraction in Java, is with interfaces.
 An interface is a completely "abstract class" that is used to group related methods with empty bodies
 An interface is a reference type. It is similar to class.
 It is a collection of abstract methods.
 A class implements an interface, thereby inheriting the abstract methods of the interface.
 It is similar to writing a class. But a class describes the attributes and behaviors of an object. And an
interface contains behaviors that a class implements.
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
Interfaces
 An interface is similar to a class in the following ways :
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface matching the
name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure
that matches the package name.
 However, an interface is different from a class in several ways, including :
 You cannot instantiate an interface.
 It does not contain any constructors and the methods in an interface are abstract.
 It cannot contain instance fields. The only fields that can appear in an interface must be declared both
static and final.
 It is not extended by a class; it is implemented by a class.
 It can extend multiple interfaces.
Example-1 : Java Interface
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("myMethod() from First Interface");
}
}
public void myOtherMethod() {
System.out.println("myOtherMethod from Second Interface");
}}
Example-1 : Java Interface
public class Interface_Demo {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
// myMethod() from First Interface
// myOtherMethod from Second Interface
Example-2 : Java Interface
// Interface
interface Animals {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Cat implements Animals {
public void animalSound() { System.out.println("The Cat makes meow meow"); public void sleep()
{ System.out.println("Zzz"); }
}
class Dog implements Animals {
public void animalSound() { System.out.println("The Dog makes bow bow"); public void sleep()
{ System.out.println("Zzz"); }
}
Example-2 : Java Interface
class Test_Interface_Animal{
public static void main(String[] args) {
Cat c = new Cat(); c.animalSound();
Dog d = new Dog(); d.animalSound();
}
}
// The Cat makes meow meow
// The Dog makes bow bow
Example-3 : Java Interface
interface Language {
void getName(String name);
}
class ProgrammingLanguage implements Language {
public void getName(String name) {
System.out.println("Programming Language: " + name);
}
}
public class Interface_Language {
public static void main(String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage();
language.getName("Object Oriented Programming using Java");
}
}
// Programming Language: Object Oriented Programming using Java
Example-4 : Java Interface
interface Polygon { void getArea(int length, int breadth); }
class Rectangle implements Polygon {
public void getArea(int length, int breadth) {
System.out.println("The area of the rectangle is " + (length * breadth));
}
}
class Square implements Polygon {
public void getArea(int s1, int s2 ) {
System.out.println("The area of the square is " + (s1 * s2));
}
}
Example-4 : Java Interface
public class Test_Interface_Figures {
public static void main(String[] args) {
// create an object
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
Square s1 = new Square();
s1.getArea(4,4);
}
}
// The area of the rectangle is 30
// The area of the square is 16
Java Encapsulation
 It is a process of wrapping code and data together into a single unit.
 For Example, a capsule which is mixed of several medicines.

 The meaning of Encapsulation, is to make sure that "sensitive" data is


 hidden from users.
 Advantages :
 It provides us to control over the data.
 It is a way to achieve data hiding.
 Easy to Test (Unit Testing).
Example-1: Encapsulation
class Area {
// fields to calculate area
int length, breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length; this.breadth = breadth;
}
// method to calculate area
public void getArea() {
int area = length * breadth;
System.out.println("Area: " + area);
}
}
Example-1: Encapsulation
class AreaEncapsulation {
public static void main(String[] args) {
// create object of Area
// pass value of length and breadth
Area rectangle = new Area(5, 6);
rectangle.getArea();
}
}
Example-2: Encapsulation
// Data hiding using the private specifier
class Person {
private int age; // private field
public int getAge() { return age; } // getter method
public void setAge(int age) { this.age = age; } // setter method
}
class Person_Encapsulate{
public static void main(String[] args) {
Person p1 = new Person(); // create an object of Person
p1.setAge(24); // change age using setter
// access age using getter
System.out.println("My age is " + p1.getAge());
}
}
// My age is 24
Example-3: Encapsulation
// STUD.java in which Java class is fully encapsulated class.
public class STUD{
private String Name; //private data member
public String getName(){ //getter method for name
return Name;
}
public void setName(String name){ //setter method for name
this.Name=name;
}
}
Example-3: Encapsulation
class Student{
public static void main(String[] args){
//creating instance of the encapsulated class
STUD s=new STUD();
//setting value in the name member
s.setName(“Balasundaram A");
//getting value of the name member
System.out.println(s.getName());
}
}

//Balasundaram A
Example-4: Encapsulation
// Account.java : A Account class which is a fully encapsulated class.
class Account {
private long acc_no; //private data members
private String name,email;
private float amount;
//public getter and setter methods
public long getAcc_no() { return acc_no; }
public void setAcc_no(long acc_no) { this.acc_no = acc_no; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public float getAmount() { return amount; }
public void setAmount(float amount) { this.amount = amount; }
}
Example-4: Encapsulation
// Acc_Encapsulation.java : Testing the encapsulated class Account.
public class Acc_Encapsulation {
//A Java class to test the encapsulated class Account.
public static void main(String[] args) {
//creating instance of Account class
Account acc=new Account();
//setting values through setter methods
acc.setAcc_no(9841288826);
acc.setName(“Balasundaram A");
acc.setEmail(“[email protected]");
acc.setAmount(500000f);
//getting values through getter methods
System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" }
}
// 9841288826 Balasundaram A [email protected] 500000.0
Java Inheritance
 Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
 It is an important part of OOPs (Object Oriented programming system).
 The class which inherits the properties of other is known as subclass (derived class,
child class).
 The class whose properties are inherited is known as superclass (base class, parent
class).
 Inheritance represents the IS-A relationship which is also known as a Parent-Child
relationship.
 The idea behind inheritance is to create new(Child/Sub) classes that are built upon
existing(Parent/Super) classes. By Inheriting, reuse methods and fields of the Parent
class. Moreover, you can add new methods and fields in your current class also.
extends keyword
 extends is the keyword used to inherit the properties of a class.
 Syntax:
class Super { // Parent/Base Class
.....
.....
}
class Sub extends Super { // Child/Derived Class
.....
.....
}
 A subclass can inherit all the members (fields, methods, and nested classes) from its superclass. Constructors are
not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from
the subclass.
Example-1 : Inheritance
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
/* Programmer salary is:40000.0
* Bonus of programmer is:10000 */
Example-2 : Inheritance
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println(“Hi, Welcome!");
} /* Hi, Welcome!
} * Ford Figo */

class Car extends Vehicle {


private String modelName = “Figo"; // Car attribute
public static void main(String[] args) {
Car myCar = new Car();
myCar.honk();
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Example-3 : Inheritance
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum :"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference :"+z);
}
}
Example-3 : Inheritance
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product o:"+z); /* The sum :3 0
} * The difference :10
* The product :200 */
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation C = new My_Calculation();
C.addition(a, b); C.Subtraction(a, b); C.multiplication(a, b);
}
}
Types of Inheritance

Not Supported in Java


Types of Inheritance
Example-1 : Single Inheritance
class Animal{
void eat() { System.out.println("eating..."); }
}
class Dog extends Animal{
void bark() { System.out.println("barking..."); }
} /* barking...
* eating... */
class SingletInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
Example-2 : Multilevel Inheritance
class Animal {
void eat() { System.out.println("eating..."); }
}
class Dog extends Animal {
void bark() { System.out.println("barking..."); }
} /* weeping...
* barking...
class BabyDog extends Dog { * eating... */
void weep() { System.out.println("weeping..."); }
}
class MultilevelInheritance {
public static void main(String args[]) {
BabyDog d = new BabyDog();
d.weep(); d.bark(); d.eat();
}
}
Example-3 : Hierarchical Inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
} /* meowing...
* eating... */
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class HierarchicalInheritance{
public static void main(String args[]){
Cat c=new Cat();
c.meow(); c.eat();
//c.bark(); //C.T.Error (Not permitted to access)
}
Multiple Inheritance
Why multiple inheritance is not supported in java?
 To reduce the complexity and simplify the language, Multiple inheritance is
not supported in java.
 Example : Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method and you call it
from child class object, there will be ambiguity to call the method of A or B
class.
 Since Compile-time errors are better than Runtime errors, java renders compile-
time error if you inherit 2 classes. So whether you have same method or
different, there will be compile time error.
Example-3 : Hierarchical Inheritance
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{ //suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}

// Compile Time Error


Super Keyword
 The super keyword is similar to this keyword.
 It is used to differentiate the members of superclass from the members of subclass, if they have same names.
 It is used to invoke the superclass constructor from subclass.

class Super_class {
int num = 20;
// display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
}
}
Super Keyword
public class Sub_class extends Super_class {
int num = 10;
// display method of sub class
public void display() {
System.out.println("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class
sub.display();
// Invoking the display() method of superclass
super.display();
Super Keyword
// printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:“ + sub.num);
// printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:“ + super.num);
}
public static void main(String args[]) {
Sub_class obj = new Sub_class();
obj.my_method();
}
}
Output:
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Example : Invoking super [Method Overriding]
class Animal {
// method in the superclass
public void eat() { System.out.println("I can eat"); }
}
class Dog extends Animal { // Dog inherits Animal
@Override // overriding the eat() method
public void eat() {
super.eat(); // call method of superclass
System.out.println("I eat dog food");
}
public void bark() { // new method in subclass
System.out.println("I can bark");
}
}
Example : Invoking super [Method Overriding]
class UseSuperClass {
public static void main(String[] args) {
Dog labrador = new Dog(); // create an object of the subclass
labrador.eat(); // call the eat() method
labrador.bark();
}
}

/* I can eat
* I eat dog food
* I can bark */
Example : Invoking super constructor
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age“ + "in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) { super(age); }
public static void main(String args[]) { // The value of the variable named age in super class is: 24
Subclass s = new Subclass(24);
s.getAge();
} }
Java Polymorphism
 It is an important concept of object-oriented programming.
 It simply means more than one form.
 It as the ability of a message to be displayed in more than one form.
 It is the ability of an object to take on many forms.
 Polymorphism in Java is a concept by which we can perform a single action in different ways.
 It is derived from 2 Greek words: poly and morphs.
 The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
 There are two types of polymorphism in Java:
 Compile-Time polymorphism - Static
 (Example : Method/Operator Overloading)
 But, Java doesn’t support Operator Overloading.
 Runtime polymorphism - Dynamic
 (Example : Method Overriding)
Method Overloading
 When there are multiple functions with same name but different parameters then these functions are said to be
overloaded.
 Functions can be overloaded by change in number of arguments or/and change in type of arguments.
 Why Method Overloading ?
 Suppose, a task to perform the addition of given numbers but there can be any number of arguments (let’s say
either 2 or 3 arguments for simplicity).
 In order to accomplish the task, can create two methods sum2num(int, int) and sum3num(int, int, int) for two
and three parameters respectively. However, other programmers, as well as you in the future may get confused
as the behavior of both methods are the same but they differ by name. Code length also increases.
 The better way to accomplish this task is by overloading methods. And, depending upon the argument passed,
one of the overloaded methods is called. This helps to increase the readability of the program.
Example : Method Overloading (Different types Arguments)
// Java program for Method overloading
class MultiplyFun {
// Method with 2 parameter
static int Multiply(int a, int b) { return a * b; }
// Method with the same name but 2 double parameter
static double Multiply(double a, double b) { return a * b; }
} /* 8
* 34.65 */
class MehtodOverloading {
public static void main(String[] args) {
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
Example : Method Overloading (Different No. of Arguments)
// Java program for Method overloading
class MultiplyFun {
// Method with 2 parameter
static int Multiply(int a, int b) { return a * b; }
// Method with the same name but 3 parameter
static int Multiply(int a, int b, int c) { return a * b * c; }
} /* 8
* 42 */
class Main {
public static void main(String[] args) {
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(2, 7, 3));
}
}
Example : Method Overloading (Only with 1 Argument)
class HelperService {
private String formatNumber(int value) {
return String.format("%d", value);
}
private String formatNumber(double value) {
return String.format("%.3f", value);
}
private String formatNumber(String value) { /* 500
return String.format("%.2f", Double.parseDouble(value)); * 89.993
* 550.00 */
}
public static void main(String[] args) {
HelperService hs = new HelperService();
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
} }
Method Overloading
 Important Points to remember :
 Two or more methods can have same name inside the same class if they accept different
arguments. This feature is known as method overloading.
 Method overloading is achieved by either:
 Changing the number of arguments.
 Changing the datatype of arguments.
 Method overloading is not possible by changing the return type of methods.
Method Overriding
 It is also known as Dynamic Method Dispatch.
 It is a process in which a function call to the overridden method is resolved at
Runtime and can be achieved by Method Overriding.
 It occurs when a derived class has a definition for one of the member functions
of the base class. That base function is said to be overridden.
 Rules :
 Both the superclass and the subclass must have the same method name, the same return
type and the same parameter list.
 Can’t override the method declared as final and static.
 Always override abstract methods of the superclass
 Can we access the method of the superclass after overriding?
 (Yes, using super keyword)
Example-1 : Method Overriding
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
@Override // Not Compulsory (Tells explicitly to Compiler)
public void displayInfo() { // I am a dog.
System.out.println("I am a dog.");
}
}
class MethodOverriding {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Example-2 : Method Overriding(using super)
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
public void displayInfo() {
super.displayInfo(); // Invoking Base Class Method // I am an animal.
System.out.println("I am a dog."); // I am a dog.
}
}
class MethodOverriding {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
} }
Example-3 : Method Overriding (inheritance)
class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){ // Vehicle is running
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Example-4 : Method Overriding
//To illustrate the use of Java Method Overriding
//creating a parent class.
class Vehicle{
//defining a method
void run(){ System.out.println("Vehicle is running"); }
}
class Bike extends Vehicle{ //Creating a child class
//defining the same method as in the parent class // Bike is running safely
void run(){ System.out.println("Bike is running safely"); }
public static void main(String args[]){
Bike obj = new Bike(); //creating object
obj.run(); //calling method
}
}
Example-5 : Method Overriding
//Program to demonstrate the real scenario of Java Method Overriding
class Bank{ int getRateOfInterest(){return 0;} }
//Creating child classes.
class SBI extends Bank { int getRateOfInterest(){return 8;} }
class ICICI extends Bank{ int getRateOfInterest(){return 7;} }
class AXIS extends Bank { int getRateOfInterest(){return 9;} }
//MethodOVeridding class to create objects and call the methods
class MethodOveridding{ Output:
public static void main(String args[]){ SBI Rate of Interest: 8
ICICI Rate of Interest: 7
SBI s=new SBI();
AXIS Rate of Interest: 9
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Pointer to Remember for Method Overriding
 Can we override static method?
 No, a static method cannot be overridden.
 Why can we not override static method?
 It is because the static method is bound with class whereas instance method is bound with
an object. Static belongs to the class area, and an instance belongs to the heap area.
 Can we override java main method?
 No, because the main is a static method.
Method Overloading Vs Method Overriding
Java Packages
 PACKAGE in Java is a collection of classes, sub-packages, and interfaces.
 It helps organize the classes into a folder structure and make it easy to locate and use them.
 More importantly, it helps improve code reusability.
 Each package in Java has its unique name and organizes its classes and interfaces into a separate namespace, or
name group.
 Package in java can be categorized in to two forms :
 Built-in Packages
 User-Defined Packages
 Advantages :
 It categorizes the classes and interfaces. so, they can be easily maintained.
 It provides access protection.
 It removes naming collision.
 Re-usability and Data Encapsulation
Types of Packages
Built in Packages
 The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.
 The library contains components for managing input, database programming, and much more.
 The complete list can be found at Oracles website:
 https://docs.oracle.com/en/java/javase/15/docs/api/index.html.
 The library is divided into packages and classes.
 To use a class or a package from the library, you need to use the import keyword:
 Example:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
import java.util.Scanner; // java.util is a package, while Scanner is a class of the java.util package.
Example-1 : Java Package
javac testpackages.java

The compilation is completed.


A class file testpackages is created.
However, no package is created?
User-Defined Packages
 Every class is part of some package.
 All classes in a file are part of the same package.
 You can specify the package using a package declaration: package name ; as the first (non-comment) line in the
file. It can be created using a keyword package:
 Syntax:
package nameOfPackage;
 Examples :
package MyPackages; // Meaningfull Names
package My_Packages;
 Multiple files can specify the same package name.
 If no package is specified, the classes in the file go into a special unnamed package (the same unnamed package
for all files).
 If package name is specified, the file must be in a sub-directory called name (i.e., the directory name must
match the package name).
User-Defined Packages
 To create User-Defined package, Java uses a file system directory to store them (Like Computers...).
 File Structure :

 To create a package, use the package keyword:


 javac –d . MyClass.java
 javac –d .. MyClass.java
 The -d is a switch that tells the compiler where to put the class file.
 The "." operator represents the current working directory.
 The ".." indicates the parent directory.
User-Defined Packages
 Now Compile the package :
 javac -d . MyPackageClass.java
 javac -d .. MyPackageClass.java
 The -d is a switch that tells the compiler where to put/save the class file
 The "." operator represents the current working directory.
 The ".." indicates the parent directory.
 Note : When we compiled the package as above, a new folder was created, called "mypack".
 Finally, Run the package:
 java mypack.MyPackageClass
How to access package from another package?
 There are three ways to access the package from
outside the package.
 1. import package.*;
 2. import package.classname;
 3. fully qualified name.
 Example-1 : //save by B.java
//save by A.java package mypack;
package pack; import pack.*;
public class A{ class B{
public void msg(){ public static void main(String args[]){
System.out.println("Hello"); A obj = new A();
} obj.msg();
} }
}
How to access package from another package?
 There are three ways to access the package from
outside the package.
 1. import package.*;
 2. import package.classname;
 3. fully qualified name.
 Example-2 : //save by B.java
//save by A.java package mypack;
package pack; import pack.A;
public class A{ class B{
public void msg(){ public static void main(String args[]){
System.out.println("Hello"); A obj = new A();
} obj.msg();
} }
}
How to access package from another package?
 There are three ways to access the package from
outside the package.
 1. import package.*;
 2. import package.classname;
 3. fully qualified name.
 Example-3 : //save by B.java
//save by A.java package mypack;
package pack; class B{
public class A{ public static void main(String args[]){
public void msg(){ pack.A obj = new pack.A();
System.out.println("Hello"); obj.msg();
} }
} }
Sub-Packages in Java
 Package inside the package is called the subpackage.
 It should be created to categorize the package further.
 Example : Sun Microsystem has definded a package called java that contains several classes
including System, String, Reader, Writer, Socket etc.
 These groups represent a specific category
 The classes Reader and Writer are for the operation of Input/Output.
 The classes Socket and ServerSocket are for networking etc and so on.
 Therefore, Sun sub-categorized the java package into sub-packages, such as lang, net, io, etc.
 The standard of defining package is :
 Syntax :
 domain.company.package.
 Eg : in.vit.cse1007
THANK YOU

You might also like