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

3classes and Objects - Methods - Access Specifiers & Modifiers

Classes and Objects -Methods -Access specifiers & modifiers

Uploaded by

Jitender Tanwar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

3classes and Objects - Methods - Access Specifiers & Modifiers

Classes and Objects -Methods -Access specifiers & modifiers

Uploaded by

Jitender Tanwar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Name of the School: School of Computer Science and

Engineering
Course Code: E2UC304C Course Name:Java & Java Script

DEPARTMENT OF COMPUTER SCIENCE


& ENGINEERING
Subject Name: Java Programming
Topics Covered: Classes and Objects -Methods -Access
specifiers & modifiers

1
Faculty Name: Programe Name: B.Tech (CSE,AI &ML)
List of Topics to be covered
Object-Oriented Programming
Class in Java
How to define a class in Java?
Java Program

Access Modifiers:
Java Access Modifiers
Access Modifiers and its access

2
Object Oriented Programming
Java is an object-oriented programming language

As the term implies, an object is a fundamental entity


in a Java program
Objects can be used effectively to represent real-world
entities
For instance, an object might represent a particular
employee in a company
Each employee object handles the processing and data
management related to that employee
3
Class in Java
A class is an entity that determines how an object will behave and
what the object will contain.
An object is defined by a class

A class is the blueprint of an object

The class uses methods to define the behaviors of the object

The class that contains the main method of a Java program


represents the entire program
A class represents a concept, and an object represents the
embodiment of that concept
4 Multiple objects can be created from the same class
Class in Java

5
Java Class Contains
A class in Java can contain:
fields
methods
constructors
blocks
nested class and
interface

6
Object
An object has:
state - descriptive characteristics

behaviors - what it can do (or what can be done to it)

 The state of a bank account includes its account number and its current balance

 The behaviors associated with a bank account include the ability to make
deposits and withdrawals
 Note that the behavior of an object might change its state

7
Object (Contd…)
 An object is nothing but a self-contained component which consists of methods and
properties to make a particular type of data useful. Object determines the behavior of
the class. When you send a message to an object, you are asking the object to
invoke or execute one of its methods.
 From a programming point of view, an object can be a data structure, a variable or a
function. It has a memory location allocated. The object is designed as class
hierarchies.
What is the difference between Object & class?
 A class is a blueprint or prototype that defines the variables and the methods
(functions) common to all objects of a certain kind.
 An object is a specimen of a class. Software objects are often used to model real-
world objects you find in everyday life.

8
Object & Class

9
Class Methods

10
Class and Members

So far we have defined


following things:

Class - Dogs
Data members - breed,
size, color, age etc.
Methods- eat(), run(),
sleep().

11
12
Person Class

13
How to define a class in Java?

class ClassName
{
// variables
// methods
}

14
Object Creation in Java
An object is called an instance of a class. For example, suppose Animal
is a class then Cat, Dog, Horse, and so on can be considered as objects
of Animal class.

Here is how we can create objects in Java:


Syntax:
className object = new className();

Here, we are using the constructor className() to create the object.


Constructors have the same name as the class and are similar to
15
methods
Java Program

16
public class Dog {
String breed, size; color; / / instance variable
int age;
Java public static void main(String[] args) {
Program // create object here
Dog Dog1Object = new Dog();
Dog Dog2Object = new Dog();
Dog Dog3Object = new Dog();

// Data input for Dog Object 1


Dog1Object.breed = "Beagle";
Dog1Object.size = "Large";
Dog1Object.color = "Light Gray";
17 Dog1Object.age = 5;
Java Program (Contd…)
Dog2Object.breed = "Buldog"; // Data input for Dog Object 2
Dog2Object.size = "Large";
Dog2Object.color = "Orange";
Dog2Object.age = 6;
Dog3Object.breed = "German Shepherd"; // Data input for Dog Object 3
Dog3Object.size = "large";
Dog3Object.color = "white and Orange";
Dog3Object.age = 6;
// print all data from objects
System.out.println("Dog Object 1: \n Breed: "+Dog1Object.breed+"\n Size: "+Dog1Object.size+"\n Color: "+Dog1Object.color+"\n Age:
"+Dog1Object.age);
System.out.println("Dog Object 2: \n Breed: "+Dog2Object.breed+"\n Size: "+Dog2Object.size+"\n Color: "+Dog2Object.color+"\n Age:
"+Dog2Object.age);
System.out.println("Dog Object 3: \n Breed: "+Dog3Object.breed+"\n Size: "+Dog3Object.size+"\n Color:
"+Dog3Object.color+"\n Age: "+Dog3Object.age);
}}

18
main() method within the class
class Student{
String name; //field or data member or instance variable
int rollNo;//field or data member or instance variable

public static void main(String args[]){


Student s1=new Student(); //creating an object of Student
System.out.println(s1.name); //accessing member through
reference variable
System.out.println(s1.rollNo); //accessing member through
reference variable
}
}
Output: It gives null and 0 output because we know that default value
null number is 0 and for object references it is null.
19 0
Main() method outside a class
We create classes and use it from another class using instance of that
class(object).
It is a better approach than previous one. Let's see a simple example, where
we are having main() method in another class.

We can have multiple classes in different java files or single java file.
If you define multiple classes in a single java source file, it is a good idea to
save the file name with the class name which has main() method.

20
Program: Main() method outside a class
class Student{
String name; //field or data member or instance variable
int rollNo;//field or data member or instance variable
}
class MainClass{ //this is main class
public static void main(String args[]){
Student s1=new Student(); //creating an object of Student
System.out.println(s1.name); / /accessing member through
reference variable
System.out.println(s1.rollNo); //accessing member through
reference variable
}
} It gives null and 0 output because we know that default value number is 0 and for object references it is null.
21
Initialize object

There is three Ways to initialize object


By reference variable
By method
By constructor

22
Initialization through reference
class Student{
String name; //field or data member or instance variable
int rollNo;//field or data member or instance variable
}

class MainClass{
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
s1.name = "Ram"; //Initialization through reference
s1.rollNo = 21; // Initialization through reference
System.out.println(s1.name+"'s Roll No: "+s1.rollNo);
Output:
} Ram's Roll No: 21
23
}
Initialization through method
class Student{
String name; //field or data member or instance variable
int rollNo;//field or data member or instance variable

void methodforInti(String name, int rollNo)


{ Output:
this.name = name; Ram's Roll No:
21
this.rollNo = rollNo;
}
public static void main(String args[]){
Student obj1=new Student();
obj1.methodforInti("Ram",21);
System.out.println(obj1.name+"'s Roll No: "+obj1.rollNo);
24 }}
Initialization & display through method
class Student{
String name; //field or data member or instance variable
int rollNo;//field or data member or instance variable
void methodforInti(String s, int r)
{
name = s;
rollNo = r; Output:
} Ram's Roll No: 21
void methodforDisplay()
{
System.out.println(name+"'s Roll No: "+rollNo);
}
public static void main(String args[]){
Student obj1=new Student();
obj1.methodforInti("Ram",21);
obj1.methodforDisplay();
25 }}
Initialization through a constructor
class Student{
String name; //field or data member or instance variable
int rollNo;//field or data member or instance variable
Student(String s, int r) // this is a constructor
{
name = s;
rollNo = r; Output:
Ram's Roll No: 21
}
void methodforDisplay()
{
System.out.println(name+"'s Roll No: "+rollNo);
}
public static void main(String args[]){
Student obj1=new Student("Ram",21);
obj1.methodforDisplay();
26 }}
Java Access Modifiers

public, private and protected keywords are very common in java


programs, these are called access modifiers.
An access modifier restricts the access of a class, constructor, data
member and method in another class.

 In java we have four access modifiers:


1. default
2. private
3. protected
4. public
27
Access Modifiers and its access

28
1. Default access modifier
When we do not mention any access modifier, it is called default access
modifier.

The scope of this modifier is limited to the package only. This means that
if we have a class with the default access modifier in a package, only those
classes that are in this package can access this class.

No other class outside this package can access this class. Similarly, if we
have a default method or data member in a class, it would not be visible
in the class of another package.

29
Program with default Access modifier
package A; package B;
import A.*;
public class Multiplication
public class Controller {
{ public static void main(String args[])
/* As we haven't specified any {
Multiplication object = new Multiplication();
access modifier here before method,
object.Multiply(10, 21);
it will be considered as default. }
*/ }
int Multiply(int an, int b){
return a*b; Output:
} Exception in thread “main” java.lang.Error :
Unresolved compilation problem:The method
} Multiply(int, int) from the type Multiplication is not
visible at B.Controller.main(Controller.java:6)
30
protected
The protected access modifier provides access within the package and
outside the package through inheritance only i.e by creating child class
(subclass or derived class).

It cannot be accessed from outside the package if there is no


inheritance.

31
protected access Modifier
In this example, the class Controller which is available in another package
B can access the Multiply() method, which is declared as protected. This
is possible since the class Controller extends class Multiplication.
Subclasses of the Multiplication class present in any package can
access the protected methods or data members.
Controller.java
package B;
Multiplication.java
import A.*;
class Controller extends Multiplication {
package A;
/*
public class Multiplication {
* Controller is a sub-class of Multiplication
protected int multiply(int a, int b){
*/
return a*b;
public static void main(String args[]){
}
Controller object = new Controller ();
}
System.out.println(object.multiply(11, 22));
Output: }
32 33 }
Public:
The public access modifier offers the lowest level of access restriction.

Class or variable or method declared as public can be accessed


everywhere.

Once a variable or method is declared public, it can be accessed from


anywhere in the code, i.e within the class, outside the class, within the
package and outside the package.

33
Program: Public access modifier
//Multiplication.java //Controller.java
package A;
package B;
public class Multiplication { import A.*;
/*As Multiply is made public it can class Controller {
be accessed anywhere globally */ public static void main(String args[])
{
public int Multiply (int an, int b) Multiplication object = new Multiplication ();
{ System.out.println(object.Multiply(100, 2));
return a*b; }
}
}
}
Output:
34 200
Private access modifier
A private access modifier offers the highest level of access
restriction.

The access level of a private access modifier is only within the


class.

The data members and methods declared as private cannot be


accessed from outside the class.

35
Program
class A
{ Output:
private int totalValue = 50; Compilation error
private int Multiply(int a,int b) /B.java:17: error: totalValue has private access in A
{ System.out.println(object.totalValue);
return a*b; ^
}
/B.java:18: error: Multiply(int,int) has private access in A
}
public class B
System.out.println(object.Multiply(10,15));
{
public static void main(String args[])
{
A object = new A();
System.out.println(object.totalValue); //accessing private data member of class A
System.out.println(object.Multiply(10,15)); // accessing private method of class A
}}
36
Program to access private members of a class
class A2
{
private int totalValue = 50;
public class B2
private int a=10; {
private int b=20; public static void main(String args[])
private int Multiply() {
{ A2 object = new A2();
return a*b; //System.out.println(object.totalValue); //accessing private data
}
member of class A
int show()
{
//System.out.println(object.Multiply()); // accessing private
return a*b; method of class A
} System.out.println(object.show());
} }}

OUTPUT: 200

37
Important points
1. Classes in java are allowed to use only the "public" or "default" access
modifier.

2. Class members i.e variables and methods are allowed to use any of the four
access modifiers.

3. We are allowed to have only one public class in a source file. public class name
must be the same as the source file.

4. The default access modifier is also known as "package-private" or "no-


modifier".

5. Examples of non-access modifiers are static, transient, abstract, synchronized.


38
Access Modifiers in Java with method overriding
The access modifier of a overriding method(declared in a subclass) must
not be more restrictive than the access modifier of an overridden
method(declared in superclass).

In the below example class Child hello() method has a default access
modifier. It is overriding the Parent class hello() method which has a
protected access modifier.

As we know, the default access modifier is more restrictive than a


protected access modifier. Hence, the below code will throw the compile-
time error.

39
Program
class Parent
{
protected void hello() /*overridden method has protected access modifier*/
{ System.out.println("Alive is Awesome");
}
}
public class Child extends Parent
{
void hello() /*overriding method has default access modifier */
{ System.out.println("Be in present"); Output:
/Child.java:11: error: hello() in Child
}
cannot override hello() in Parent
public static void main(String args[]) { void hello()
Child obj = new Child(); ^
obj.hello(); attempting to assign weaker access privileges;
}} was protected
40 1 error
References:
 https://www.geeksforgeeks.org/
 https://www.javatpoint.com/exception-handling-in-java
 https://www.tutorialspoint.com/java/java_exceptions.htm
 The complete reference, eleventh edition, available at:
https://gfgc.kar.nic.in/sirmv-science/GenericDocHandler/1
38-a2973dc6-c024-4d81-be6d-5c3344f232ce.pdf

41
Thank you

42
43
44
45
46

You might also like