0% found this document useful (0 votes)
35 views

CH_2 Classes and Objects

Uploaded by

abhishekmane280
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

CH_2 Classes and Objects

Uploaded by

abhishekmane280
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

CH 2.

Classes and Objects


 C, Pascal, Fortran are called Procedure Oriented Programming Languages. These languages
uses procedures or functions to perform a task, functions which are called and controlled -
from a main() function.

Procedure oriented approach

Object oriented approach


 Languages like C++ and Java use classes and objects in their programs and are called Object
Oriented Programming languages. Object oriented programming approach is a programming
methodology to design computer programs using classes and objects.

Features of Object Oriented Programming System (OOPS):


 There are many features related to Object Oriented approach some of the features are:
o Class/Object
o Encapsulation
o Abstraction
o Inheritance
o Polymorphism

Class and Object


 Class
 Class is the basic building block of Java language.
 A Class is a template (specification or blueprint) that describes the data and behavior
associated with instances of that class.
OR
 “A class is a way of binding the data and associated methods in a single unit”.
 A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.

 EX1.

 EX2.
 Syntax of defining class:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{ // body of method }

type methodname2(parameter-list)
{ // body of method }
// ...
type methodnameN(parameter-list)
{ // body of method }
}

 OBJECT:
 In order to store the data for the data members of the class, we must create an object.
1. Instance of a class is known as an object. (instance is a mechanism of allocating sufficient
amount of memory space for data members of a class).
2. Class variable is known as an object.
3. Value form of a class is known as an object.
4. Logical runtime entity is known as an object.
5. Real world entities are called as objects.
6. An object is anything that really exists in the world and can be distinguished from others.
 JAVA always follows dynamic memory allocation but not static memory allocation.
 In order to create a memory space in JAVA we must use an operator called new. This new operator is
known as dynamic memory allocation operator.
 Syntax:
o ClassName obj_name=new ClassName();
OR
o ClassName obj_name; // declare reference to object or Object declaration
o Obj_name=new Classname(); // allocate memory object or object referencing
 When an object is declared it is set to a null value, since, there is no memory space.
 When the object is referenced the value of the object memory space is created for the data members
of the class
 The dot operator (.) or member selection operator is used to access the instance variables of the class.
 Syntax: obj_name.variablename
EX:
class Box
{ double width;
double height;
double depth;
}

/* A program that uses the Box class. Call this file BoxDemo.java*/

class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[])
{
Box mybox = new Box();
double vol;

// assign values to mybox's instance variables


mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;

// compute volume of box


vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}

Data Abstraction:
 Data abstraction is the process of hiding certain details and showing only essential
information to the user.
OR
 Data Abstraction is a mechanism of retrieving the essential details without dealing with
background details.

Data Encapsulation:
 Binding (or wrapping) code and data together into a single unit are known as encapsulation.
OR
 “Data encapsulation is the process wrapping data and associated methods in a single unit”.
 Data encapsulation is basically used to achieve data/information hiding i.e. security.

EX. A program that accept student details and print it.


EX. Write a program to perform arithmetic operations.
EX. Write a Class number having one data member, write methods to acceptno and to diplay
square and cube of a number.
Method Overloading
 If a class have multiple methods by same name but different parameters, it is known as Method
Overloading
Ex:
class Calculation
{
int addition(int a,int b)
{ return (a+b); }

int addition(int a,int b, int c)


{ return (a+b+c); }
float addition(float a,float b)
{ return (a+b); }

String addition(String a,String b)


{ return (a+b); }
}
class OverlaodingDemo
{
public static void main(String []args)
{
Calculation obj=new Calculation();
System.out.println(obj.addition(10,20));
System.out.println(obj.addition(10,34,20));
System.out.println(obj.addition(52.36f,23.64f));
System.out.println(obj.addition("ABC","PQR"));
}
}

EX. Write a class circle having methods to accept radius and to compute circumference and
area of circle.
Constructors
 Constructor is a special type of method that is used to initialize the state of an object.
 Constructor is invoked at the time of object creation.
 It constructs the values i.e. data for the object that is why it is known as constructor.
 Constructor is just like the instance method but it does not have any explicit return type.
Rules for creating constructor
 There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
3. Access modifier should be public
Types of constructors
There are two types of constructors:
 default constructor (no-arg constructor)
 parameterized constructor

1) Default Constructor
 A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>(){…….}
2) Parameterized constructor
A constructor that have parameter is known as parameterized constructor.
Syntac:
<class_name>(argumentlist){…….}

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct
objects.
EX:
class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan 222 Aryan

Constructor Overloading
 Constructor overloading is a technique in Java in which a class can have
any number of constructors that differ in parameter lists. The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type.
 Example of Constructor Overloading
 //Program of constructor overloading
class Student
{ int id; String name; int age;
Student()
{
id=0; name="Unknown"; age=0;
}

Student(int i,String n)
{ id = i; name = n; age=18; }

Student(int i,String n,int a)


{ id = i; name = n; age=a; }

void display()
{ System.out.println(id+" "+name+" "+age);}

public static void main(String args[])


{
Student s1 = new Student(); // will call default const.
Student s2 = new Student(111,"Karan");// call parameterized const. with 2 arg.s
Student s3 = new Student(222,"Aryan",25); // call parameterized const. with 3 arg.s
s1.display(); // 0 unknown 0
s2.display(); // 111 karan 18
s3.display(); // 222 Aryan 25
}
}
Output:
0 Unknown 0
111 Karan 18
222 Aryan 25
Constructor vs Method
 Constructor is used to initialize the state of an object.
 Method is used to expose behavior of an object.
 Constructor must not have return type.
 Method must have return type.
 Constructor is invoked implicitly.
 Method is invoked explicitly.
 The java compiler provides a default constructor if you don't have any
constructor.
 Method is not provided by compiler in any case.
 Constructor name must be same as the class name.
 Method name may or may not be same as class name.

Mutator and Accessor Methods:


- Mutator Method allows the change in value of class variables. Using mutator
methods data members of a class can be manipulated from outside the class.
- Accessor method allows to access the data members. It does not manipulate data
members;
Class Test
{
int num;
int getNum() //accessor method
{ return num;}
int setNum(int d) //mutator method
{ num=d;}
}

Array of Objects:
- Instead of creating object of particular class, we can create an array of objects.
- Syntax : ClassName[ ] arrayName = new ClassName[size];
- Syntax : ClassName arrayName[] = new ClassName[size];
-
EX: Write a program to accept student details (rno, name, percerntage) of N students and display it.(use
array of objects)
import java.util.Scanner;
class Student
{
int rollno;
String sname;
float per;

Student()
{ rollno=0; sname="Unknown"; per=0.0f; }
// OR Student(){}

Student(int rollno, String sname,float per)


{
this.rollno= rollno;
this.sname=sname;
this.per=per;
}

void display()
{
System.out.println(rollno+"\t"+sname+"\t"+per);
}
}

class StudentDemo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of Student:");
int n=sc.nextInt();
Student sArr[]=new Student[n]; //
for(int i=0;i<n;i++)
{
System.out.print("Enter RollNo:");
int rno=sc.nextInt();
System.out.print("Enter Name:");
String sname=sc.next();
System.out.print("Enter percentage:");
float per=sc.nextFloat();

sArr[i]=new Student(rno,sname,per);
}

System.out.println("Student Details Are:");


System.out.println("RollNo\t Name \t Percentage");
for(int i=0;i<n;i++)
sArr[i].display();
}

This Keyword:
this: ‘this’ is an internal or implicit object created by JAVA.
o ‘this’ object is internally pointing to current class object.
o Whenever the formal parameters and data members of the class are similar, to
differentiate the data members of the class from formal parameters, the data members
of class must be proceeded by ‘this’. (eg. this.var_name=….)
o this (): this () is used for calling current class default constructor from current class
parameterized constructors.
o this (…): this (…) is used for calling current class parameterized constructor from other
category constructors of the same class.
o Whenever we use either this () or this (…) in the current class constructors, that
statements must be used as first statement only.
Ex - Demonstration

Static Block, Variables and Methods


 Java class contains variables and methods called as instance variables and instance
methods. When object is created memory gets allocated for the variables and methods
also.
 The static keyword in Java is used for memory management.
 Static keyword can be applied to variables, methods, blocks
 Static Block:
o Static block is used to initialize the static data member.
o A class can contain static block that does not exist within a method body.
o It is executed before the main method at the time of class loading.
o Static block is also called static initialization block
o Syntax:
static{
//code for initialization of members
}
o Class can have any number of static blocks anywhere in the class. JVM combines
all these blocks into single block and then executes.
EX
public class DemoStaticBlock
{
Static
{ System.out.println("In Static Block....."); }

public DemoStaticBlock()
{ System.out.println("Default Constructor"); }

public static void main(String [] args)


{
//DemoStaticBlock obj=new DemoStaticBlock();
}
}
 Static Variables:
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
o Static variable makes program memory efficient (i.e., it saves memory).
EX1.
class Student{
int rollno; //instance variable or non-static variable
String name; //instance variable
static String college ="ICCS"; //static variable or class variable
Student(int rollno , String name){ //constructor
this.rollno = rollno ;
this.name = name;
}

//method to display the values


void display (){System.out.println(rollno+" "+name+" "+college);}
}

//Test class to show the values of objects


public class TestStaticVariable{
public static void main(String args[]){
Student obj1 = new Student(111,"AAA");
Student obj2 = new Student(222,"BBB");

obj1.display();
obj2.display();
//we can change the college of all objects by the single line of code
Student.college="Indira College";
obj1.display();
obj2.display();
}
}

EX2:
class Counter
{
static int count=0; //will get memory only once and retain its value

Counter()
{ count++; System.out.println(count); }

public static void main(String args[])


{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

 Static Methods:
o If we use static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.
 There are two main restrictions for the static method.
 The static method cannot use non static data member or call non-
static method directly.
 this and super cannot be used in static context.
o Math class static methods
public class Main {
public static void main( String[] args ) {

// accessing the methods of the Math class


System.out.println("Absolute value of -12 = " + Math.abs(-
12));
System.out.println("Value of PI = " + Math.PI);
System.out.println("Value of E = " + Math.E);
System.out.println("2^2 = " + Math.pow(2,2));
}
}
o EX1 :
import java.util.Scanner;
import java.lang.*;
class ArithStatic
{
public static int addition(int a, int b)
{ return (a+b); }

public static int subtraction(int a, int b)


{ return (a-b); }

public static int multiplication(int a, int b)


{ return (a*b); }

public static int division(int a, int b)


{ return (a/b); }

public static int mod(int a, int b)


{ return (a%b); }
}

class ArithStaticDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter two Numbers:");
int num1 = sc.nextInt();
int num2= sc.nextInt();

System.out.println(num1+ " + "+num2 +"="+ ArithStatic.addition( num1,num2));


System.out.println(num1+ " - "+num2 +"="+ ArithStatic.subtraction( num1,num2));
System.out.println(num1+ " * "+num2 +"="+ ArithStatic.multiplication( num1,num2));
System.out.println(num1+ " / "+num2 +"="+ ArithStatic.division( num1,num2));
System.out.println(num1+ " % "+num2 +"="+ ArithStatic.mod( num1,num2));
}
}
Output:
Enter two Numbers:15 14
15 + 14=29
15 - 14=1
15 * 14=210
15 / 14=1
15 % 14=1
o EX2 :
public class StaticEx {
public static int count = 0;

public static void displayCnt() {


System.out.println("Count: " + count);
}

public static void main(String[] args) {


StaticEx .displayCnt(); // Output: Count: 0
StaticEx .count++;
StaticEx .displayCnt(); // Output: Count: 1
}
}
Output:
Count: 0
Count: 1
Predefined Classes:
Object Class:
- The Object class, defined in the java.lang package, defines and implements behavior common
to all classes—including the ones that you write.
- the Object class is the root of the class hierarchy. Every class in Java implicitly extends the
Object class if no other super-class is specified. This means that every class in Java inherits the
methods of the Object class.
- Methods of the Object Class
o public boolean equals(Object obj) –
 Determines whether two objects are equal.
o public String toString() –
 Returns a string representation of the object.
 By default, it returns a string consisting of the class name and hash code, but can be
overridden to provide a meaningful string representation.
o public int hashCode()
 Returns a hash code value for the object.
 hash code is used in hashing data structures like HashMap, HashSet etc.
o public final Class<?> getClass()
 Returns the runtime class of the object.
o public final void notify()
 Wakes up a single thread that is waiting on the object's monitor.
o public final void notifyAll()
 Wakes up all threads that are waiting on the object's monitor.
o public final void wait(long timeout) throws InterruptedException
 Causes the current thread to wait until it is notified or interrupted, or until a
specified amount of time has elapsed.
o protected void finalize() throws Throwable
 Called by the garbage collector before the object is garbage collected. Deprecated
since Java 9.
o EX:
class Test
{ int a, b;
public Test(int a, int b)
{ this.a=a;
this.b=b;
}
void didplay()
{ System.out.println("a="+a+" b="+b); }
}

class TestObjectClass
{
public static void main(String [] args)
{
Test obj1=new Test(10,20);
Test obj2=new Test(10,20);
System.out.println("toString Method= "+ obj1.toString()) ;
System.out.println("getClass Method= "+ obj1.getClass()) ;
System.out.println("hasCode Method= "+ obj1.hashCode()) ;
System.out.println("equals Method= "+ obj1.equals(obj2));
Test obj3=obj1;
System.out.println("equals Method= "+ obj1.equals(obj3));
}
}
OutPut:
toString Method= Test@5acf9800
getClass Method= class Test
hasCode Method= 1523554304
equals Method= false
equals Method= true
String and StringBuffer Class:
- In Java, String and StringBuffer are classes used for handling text. Both serve the purpose
of manipulating character strings, but they have different characteristics and use cases. Here’s a
detailed comparison and explanation of String and StringBuffer:
- String Class
o Characteristics
 Immutable: Once a String object is created, it cannot be changed. Any
modification to a string creates a new String object.
 Common Methods
 Length: int length()
 Concatenation: String concat(String str)
 Character Access: char charAt(int index)
 Substring: String substring(int beginIndex, int endIndex)
 Equality Check: boolean equals(Object obj), boolean
equalsIgnoreCase(String anotherString)
 Comparison: int compareTo(String anotherString), int
compareToIgnoreCase(String anotherString)
 Search: int indexOf(String str), boolean
contains(CharSequence s)
EX:
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1.concat(" World"); // Creates a new String "Hello World"

System.out.println(str1); // Output: Hello


System.out.println(str2); // Output: Hello World
}
}
- StringBuffer Class
o Characteristics
 Mutable: StringBuffer objects can be modified after they are created.
Methods provided by StringBuffer modify the buffer itself without creating
new objects.
 Common Methods
 Length and Capacity: int length(), int capacity()
The capacity() method of the StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
 Append: StringBuffer append(String str), StringBuffer
append(char c)
 Insert: StringBuffer insert(int offset, String str)
 Delete: StringBuffer delete(int start, int end),
StringBuffer deleteCharAt(int index)
 Reverse: StringBuffer reverse()
 Set Length: void setLength(int newLength)
EX:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies the original StringBuffer

System.out.println(sb); // Output: Hello World


}
}
NOTE:
 String: Use when the content is not going to change. Since String is immutable, it's more
efficient in scenarios where strings are not modified frequently.
 StringBuffer: Use when the content is going to change frequently, especially in a multi-
threaded environment.

Formatting String data using format() in java


- String.format() method is used to create formatted strings. It works similarly to the
printf function in C and allows you to format strings using format specifiers. This method is
useful for creating strings that require specific formatting.
- Syntax: String formattedString = String.format(String format, Object... args);
- format: A format string that specifies how the objects should be
formatted.
- args: The arguments that need to be formatted.
- Common Format Specifiers
 %d: Integer
 %f: Floating point number
 %s: String
 %c: Character
 %b: Boolean
 %x: Hexadecimal integer
 %e: Scientific notation for floating point numbers
EX:
class FormatMethod
{
public static void main(String [] args)
{
int num = 123;
String formattedString = String.format("The number is %d", num);
System.out.println(formattedString);
double pi = 3.14159;
formattedString = String.format("Pi to two decimal places: %.2f", pi);
System.out.println(formattedString); // Output: Pi to two decimal places: 3.14

String name = "Indira";


formattedString = String.format("Hello, %s!", name);
System.out.println(formattedString);

String sname = "AAA";


int age = 23;
double score = 95.12345;

formattedString = String.format("Name: %s, Age: %d, Score: %.2f", sname, age, score);
System.out.println(formattedString);
}
}
Output:
The number is 123
Pi to two decimal places: 3.14
Hello, Indira!
Name: AAA, Age: 23, Score: 95.12

Wrapper classes
- Wrapper classes in Java provide a way to use primitive data types as objects.
- They are part of the java.lang package and are used to convert primitive data types into
objects. This process is known as "boxing," and the reverse process (converting an object back
to a primitive type) is called "unboxing."
- Key Features of Wrapper Classes
o Immutability: Wrapper class objects are immutable, meaning their values cannot be
changed once they are created.
o Nullability: Unlike primitives, wrapper class objects can be null.
o Utility Methods: Wrapper classes provide several utility methods for converting
between different data types, parsing strings, etc. Wrapper classes provide utility
methods such as parseXxx, valueOf, toString etc.
o Constant Fields: Wrapper classes contain constant fields like MAX_VALUE and
MIN_VALUE to represent the maximum and minimum values of the primitive types.
- Eight primitive data types in Java and their corresponding wrapper classes:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
EX:
public class IntergerWrapperEx {
public static void main(String[] args) {
// Autoboxing: primitive to wrapper
int numPr1= 555; // this is primitive int
Integer numW1= numPr1; // Autoboxing

// Unboxing: wrapper to primitive


Integer numW2= new Integer(10);
int numPr2= numW2; // Unboxing

System.out.println("Wrapper Integer: " + numW1); // Output: Wrapper Integer: 5


System.out.println("Primitive int: " + numPr2); // Output: Primitive int: 10
}
}
Output:
Wrapper Integer: 555
Primitive int: 10

Packages
A package is a collection of related classes and interfaces. It provides a mechanism for
compartmentalizing classes. The Java API is organized as a collection of several predefined packages.
The java.lang package is the default package included in all java programs. The commonly used
packages are: java.lang, java.util, java.io, and java.net
Types of Packages
1. Built-in Packages: These are packages that come with the Java Development Kit (JDK). Examples
include java.lang, java.util, java.io, and java.net.
2. User-defined Packages: These are packages created by programmers to organize their own
classes and interfaces.
Creating a package:
- To create a user defined package, the package statement should be written in the source code
file.
- This statement should be written as the first line of the program. Save the program in a
directory of the same name as the package.
o Syntax : package packageName;
- Accessing a package: To access classes from a package, use the import statement.
o Syntax :
import packageName.*; //imports all classes
import packageName.className; //imports specified class
o Note that the package can have a hierarchy of sub-packages. In that case, the package
name should be qualified using its parent-packages while importing sub-packages.

EX: Lab Book Sample code….P1 P2 PackageTest.

EX: Math Pack….


Access Modifiers in Java
1. Private access modifier
2. Default access modifier
3. Protected access modifier
4. Public access modifier

There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.
Access within class within package outside package by outside package
Modifier subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

1. Private: The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is a compile-time
error.
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
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class.
For example:
class A{
public 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
}
}
2. Default: If you don't use any modifier, it is treated as default by default. The default
modifier 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.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
public void msg(){System.out.println("Hello");}
}
//save by 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
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3. Protected:
- The protected access modifier is accessible within package and outside the package but
through inheritance only.
- The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
- It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have 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 method 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{
protected void msg(){System.out.println("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();
}
}
Output:Hello

4. Public:
- The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
- Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

You might also like