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

4. OOP in Java - Part 2

The document discusses key concepts of Object-Oriented Programming (OOP) in Java, including the use of the static keyword, access control through access modifiers, and the final keyword for constants. It also covers nested and inner classes, command-line arguments, variable-length arguments (varargs), local variable type inference, and garbage collection. These topics provide essential insights into Java programming practices and memory management.

Uploaded by

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

4. OOP in Java - Part 2

The document discusses key concepts of Object-Oriented Programming (OOP) in Java, including the use of the static keyword, access control through access modifiers, and the final keyword for constants. It also covers nested and inner classes, command-line arguments, variable-length arguments (varargs), local variable type inference, and garbage collection. These topics provide essential insights into Java programming practices and memory management.

Uploaded by

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

OOP through

Java
static keyword
 To define a class member that will be used independently of any object of
that class
 When a member is declared static, it can be accessed before any objects of
its class are created, and without reference to any object.
 Can declare both methods and variables to be static
 Instance variables declared as static are, essentially, global variables.
 When objects of its class are declared, no copy of a static variable is made.
Instead, all instances of the class share the same static variable.
 Methods declared as static have several restrictions:

They can only directly call other static methods of their class.

They can only directly access static variables of their class.

They cannot refer to this or super in any way.
 if you wish to call a static method from outside its class, you can do so
using the following general form:
classname.method( )
2
static keyword

3
Introducing Access Control
 Encapsulation provides another important attribute:
Access control.
 Through encapsulation, you can control what parts of a
program can access the members of a class.
 By controlling access, you can prevent misuse.
 How a member can be accessed is determined by the access
modifier attached to its declaration.
 Some aspects of access control are related mostly to
inheritance or packages. (A package is, essentially, a grouping
of classes.)
 Java’s access modifiers are public, private, and protected.
 Java also defines a default access level.
 protected applies only when inheritance is involved. 4
Introducing Access Control
 In the classes developed so far, all members of a class have used
the default access mode.
 Sometimes we want to restrict access to the data members of
a class— allowing access only through methods.
 Also, there will be times when you will want to define
methods that are private to a class.
 An access modifier precedes the rest of a member’s type
specification - is, it must begin a member’s declaration
statement. public int i;
private double j;
private int myMethod(int a, char b) { //...

5
The access of either a class or a member or both in java can be declared with the
help of Access Modifiers.

Types of Access Level

1. Class Level Access- Access given to a class whether to be visible outside


of package etc.
2. Member Level Access- Access given to a method of a class whether to
work outside of class or package or inside a child class etc.
1. Class Level

Modifier Within Within Outside


class package package
public Yes Yes Yes

default Yes Yes No


2. Member Level
• The class must be public if we use either
protected or public methods, as the class
must be available in the outer packages
before we use its members.
• Even though you have at least either one
public or protected method it is a must to
declare the class as public.
2. Member Level

Public Class

Must
Must
May
May
1
Non Access Modifiers

• There are other modifiers but they


are non-access modifiers that is
they provide information about
object instantiation or permission
override, etc. but are not used for
declaring access.
1. Static
2. final
3. Abstract
4. strictfp
final keyword
 A field can be declared as final to prevents its contents from being
modified, making it, essentially, a constant.
 You can do this in one of two ways:

First, you can give it a value when it is declared.

Second, you can assign it a value within a constructor.

The first approach is probably the most common.
 Here is an example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
 In addition to fields, both method parameters and local variables can
be declared final.
 Declaring a parameter final prevents it from being changed within the
method.
 Declaring a local variable final prevents it from being assigned a value
more than once
 final can also be applied to methods, class and is explained when 4
Can I have more than one public class in a file?
Nested and Inner Classes
 It is possible to define a class within another class; such classes are known
as nested classes
 The scope of a nested class is bounded by the scope of its enclosing class
 Thus, if class B is defined within class A, then B does not exist
independently of A
 A nested class has access to the members, including private members, of the
class in which it is nested
 However, the enclosing class does not have access to the members of
the nested class
 A nested class that is declared directly within its enclosing class scope is
a member of its enclosing class

1
Nested and Inner Classes
 There are two types of nested classes: static and non-static
 A static nested class is one that has the static modifier applied
 Because it is static, it must access the non-static members of its enclosing
class through an object - it cannot refer to non-static members of its enclosing
class directly
 Because of this restriction, static nested classes are seldom used.
 The most important type of nested class is the inner class
 An inner class is a non-static nested class
 It has access to all of the variables and methods of its outer class and may
refer to them directly in the same way that other non-static members of the
outer class do.
 It is also possible to declare a nested class that is local to a block.

1
inner classes within any block
scope

 nested classes are not applicable to all situations, they


are particularly helpful when handling events 10
Command-Line Arguments

A command-line argument is an input passed to a Java program when it is


executed from the terminal or command prompt. It allows users to provide
inputs without modifying the program's source code.
•In Java, command-line arguments are passed as
String array (String[] args) to the main method.
•Each argument is stored as a string in the args array.
•The number of arguments is determined by args.length.

18
Use of CommandLine Args

Dynamic Input: No need to modify code for different inputs.


Script Automation: Used in shell scripts or batch files for automated execution.
Configuration Flexibility: Ideal for setting file paths, modes, and execution
parameters.
Efficiency: Reduces the need for manual user input in interactive mode
Varargs: Variable-Length
Arguments
 A method can have “normal” parameters along with a variable-
length parameter.
 However, the variable-length parameter must be the last parameter declared
by the method.

 For example, this method declaration is perfectly acceptable:


int doIt(int a, int b, double c, int ... vals) {
 In this case, the first three arguments used in a call to doIt( ) are matched to the first
three parameters.
 Then, any remaining arguments are assumed to belong to vals.
 For example, the following declaration is incorrect:
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
 there must be only one varargs parameter.
 int doIt(int a, int b, double c, int ... vals, double ... morevals)
{ // Error!
20
Varargs: Variable-Length
 Arguments
A method that takes a variable number of arguments is called a variable-
arity method, or simply a varargs method.
 Beginning with JDK 5, Java has included this feature

21
Overloading Vararg Methods
//Varargs and
overloading.
class VarArgs3
{
static void
vaTest(int
... v)
{
System.out.print("vaTest(int ... ): "+ "Number of args:
" + v. length + "Contents: "); for(int x : v)
System. out. print
(x + " ") ;
System.out.println();
}
static void
vaTest(boolean ... v)
{
System.out.print("vaTest(boolean ... ) " + "Number of
args: " + v. length + "Contents: "); for(boolean x : v)
System. out. print
(x + " ") ;
System.out.println();
}
static void vaTest(String
msg, int ... v)
{
System.out.print("vaTest(String, int ... ):"+
msg + v.length + "Contents: "); for ( int x : v)
System. out. print
(x + " ") ;
System.out.println();
}
public static void
main(String args[])
{
vaTest(1, 2, 3);
vaTest(“Testing”,
10, 20); 22
23
Type Inference with Local
 Variables
Recently, an exciting new feature called local variable type inference was added to
the Java language.
 Beginning with JDK 10, it is now possible to let the compiler infer the type of a local
variable based on the type of its initializer, thus avoiding the need to explicitly
specify the type
 local variable type inference has become a common part of the
contemporary programming environment
 type inference, the context-sensitive identifier var was added

var counter; // Wrong! Initializer required.

var avg = 10.0;

int var = 1; // In this case, var is simply a user-defined identifier.

var myArray = new int[10]; // This is valid.

var[] myArray = new int[10]; // Wrong

var myArray[] = new int[10]; // Wrong

var myArray = { 1, 2, 3 }; // Wrong
 Only one variable can be declared at a time;
 a variable cannot use null as an initializer; and the variable being declared
 cannot be used by the initializer expression
24
Local Variable Type Inference with
Reference Types
 Earlier examples have shown type inference with primitive types, but it
can also be used with reference types.
var myStr = "This is a string";
 one of the benefits of local variable type inference is its ability to streamline
code, and it is with reference types where such streamlining is most
apparent.
 The reason for this is that many class types in Java have rather long names.
FileInputStream fin = new FileInputStream("test.txt");
 With the use of var, it can now be written like this:
var fin = new FileInputStream("test.txt");

25
Local Variable Type Inference with
Reference Types

1. Cannot be used for method parameters or return types.

2. Cannot be used without an initializer.

3. Cannot be null without an explicit type.

26
Local Variable Type Inference with
Reference Types

27
Garbage Collection
 Since objects are dynamically allocated by using the new operator, you might
be wondering how such objects are destroyed and their memory released for
later reallocation
 In some languages, such as traditional C++, dynamically allocated objects
must be manually released by use of a delete operator
 Java takes a different approach; it handles deallocation for you automatically
 The technique that accomplishes this is called garbage collection
 It works like this: when no references to an object exist, that object is assumed to
be no
longer needed, and the memory occupied by the object can be reclaimed
 There is no need to explicitly destroy objects
 Garbage collection only occurs sporadically (if at all) during the execution of
your program
 It will not occur simply because one or more objects exist that are no longer used
 Furthermore, different Java run-time implementations will take varying
approaches to garbage collection, but for the most part, you should not have to think
about it while writing your programs
28
Object Lifetime and Garbage
collection
Object Lifetime and garbage collection

 Garbage Collection is the process of reclaiming the runtime unused


memory by destroying the unused objects.
 The lifetime of an object is the time from when it is created to the time it
is garbage collected.

29

You might also like