0% found this document useful (0 votes)
16 views27 pages

Session 3

The document discusses accessing class members in Java, focusing on the use of access specifiers (private, protected, public) and access modifiers (static, final, etc.) to control visibility and memory management. It provides examples of static variables and methods, explaining their behavior and restrictions, as well as the role of constructors and the importance of the main method. Additionally, it outlines the structure of a Java program and the components of Java architecture, emphasizing the language's features and building blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views27 pages

Session 3

The document discusses accessing class members in Java, focusing on the use of access specifiers (private, protected, public) and access modifiers (static, final, etc.) to control visibility and memory management. It provides examples of static variables and methods, explaining their behavior and restrictions, as well as the role of constructors and the importance of the main method. Additionally, it outlines the structure of a Java program and the components of Java architecture, emphasizing the language's features and building blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Accessing Class Members

Scenario:

Might need to hide


sensitive information
outside the
ClassicJumble class,
such as the jumbled-up
words to be displayed
to the game user.

Sam
Accessing Class Members (Contd.)
Scenario (Contd.):

To cater to the preceding


requirement and improve the
security of a class, Sam can use
access specifiers and modifiers in
Java.
Using Objects
Objects are used to access the members of a class.
The following code snippet shows how to access the data members
of a class:
object_name.data_member_name
Using Access Specifiers
An access specifier controls the access of class members.
The various types of access specifiers in Java are:

private

protected

public
Using Access Specifiers (Contd.)
The private access specifier allows a class to hide its member
variables and member methods from other classes.
The private members of a class are not visible outside a class.
They are visible only to the methods of the same class.
A top level class cannot be declared private in Java.
The following code snippet shows how to declare a data member of
a class as private:
private <data type> <variable name>;
An inner class can be declared private.
The class members with the protected access specifier can be
accessed by all the classes within the package and by the
subclasses outside the package.
Using Access Specifiers (Contd.)
The following code snippet shows how to declare a data member of
a class as protected:
protected <data type> <variable name>;
The class members with the public access specifier can be
accessed by classes present within the package or outside the
package.
You can access a public class, data member, or method within the
class in which they are defined, from the classes defined in the
same package or outside the package.
The following code snippet shows how to declare a data member of
a class as public:
public <data type> <variable name>;
Using Access Modifiers
Access modifiers:
Determine or define how the data members and methods are used in
other classes and objects.
Determine how the data members are used and modified by other
classes.
Using Access Modifiers (Contd.)
The various modifiers permitted in Java are:

final static abstract

native synchronized transient

volatile strictfp
The static keyword :

in Java is used for memory management mainly. We


can apply java static keyword with variables, methods,
blocks and nested class. The static keyword belongs to
the class than an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
Java static variable
 If you declare any variable as static, it is
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
example, 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 of static variable
 It makes your program memory
efficient (i.e., it saves memory).
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
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(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
 Program of counter by static variable
 As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.
 //Java Program to illustrate the use of static variable which
 //is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
 Java static method
 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a
class.
 A static method can access static data member and can change the value of it.
 Example of static method
 //Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
//Java Program to get the cube of a given number using the static method

class Calculate{
static int cube(int x){
return x x x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
Restrictions for the static method
There are two main restrictions for the static method. They are:
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);
}
}
Q) Why is the Java main method static?

It is because the object is not required to call a static method. If it were a


non-static method, JVM creates an object first then call main() method that will lead
the problem of extra memory allocation.

3) Java static block

Is used to initialize the static data member.


It is executed before the main method at the time of class loading.
Example of static block
class A2{
static{
System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Q) Can we execute a program without main() method?
No, one of the ways was the static block, but it was possible till
JDK 1.6. Since JDK 1.7, it is not possible to execute a java class
without the main method.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:
static block is invoked
Since JDK 1.7 and above, output would be:
Error: Main method not found in class A3, please define the
main method as: public static void main(String[] args) or a
JavaFX application class must extend
javafx.application.Application
Just a minute
Which one of the following options is called automatically when a
class is instantiated?
Constructor
Variable
Abstract method
Package
Just a minute (Contd.)
Solution:
Constructor
Activity 1.1: Creating and Executing a Class
Problem Statement:
ProGame Corporation has recently introduced a new department
involved in the development of games. The organization has hired
junior programmers for this department. They have been assigned a
project to develop the Hangman Game application in Java. Create the
class structure for the Hangman game. In addition, write the code to
display a menu that provides a player with the options to play the
game, view the game instructions, or exit the game. Also, accept a
menu input from the user and display it. Help the programmer to
achieve the preceding requirements.
Activity 1.1: Creating and Executing a Class (Contd.)
Solution: To perform the activity, refer the steps given in the
embedded document.

Microsoft Word
Document
Summary
In this session, you learned that:
Java provides powerful features that make it a popular and widely used
programming language. Some of these features are:
Simple
Object-oriented
Platform independence
Portable
Distributed
Secure
Robust
Multithreaded
Summary (Contd.)
The various components of the Java architecture are:
Source file
Class file
JVM
API
A program in Java comprises the following building blocks:
Classes
Data types
Class members
Packages
A class defines the characteristics and behavior of an object.
Keywords are the reserved words with a special meaning for a
language, which express the language features.
Summary (Contd.)
There are eight primitive data types in Java, which are further grouped
into the following categories:
Integer type
Floating point type
Boolean type
Character type
A wrapper class acts like an object wrapper and encapsulates the
primitive data types within the class so it can be treated like an object.
In Java, a class can contain the following members:
Variables
Methods
Objects
Inner classes
Summary (Contd.)
A variable represents a name that refers to a memory location where
some value is stored.
A method is a set of statements that is intended to perform a specific
task.
Constructors are used to construct an object of a class and initialize it.
An object is an instance of a class and has a unique identity.
A package is a collection of classes.
Objects are used to access the members of a class.
An access specifier controls the access of class members. The various
types of access specifiers in Java are:
private
protected
public
Summary (Contd.)
Access modifiers determine or define how the data members and
methods are used in other classes and objects.
The various modifiers permitted in Java are:
final
static
abstract
native
synchronized
transient
volatile
strictfp

You might also like