[go: up one dir, main page]

0% found this document useful (0 votes)
34 views30 pages

7-A Closer Look at Classes and Methods-2

The document discusses recursion in Java. Recursion is when a method calls itself. A recursive method must have a base case to stop the recursion. The document provides an example Factorial class with a recursive fact method that calculates factorials. It calls itself with decreasing values of n until the base case of n == 1 is reached. The main method calls the fact method on instances of Factorial to calculate 3!, 4!, and 5!.

Uploaded by

aakarsh204
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)
34 views30 pages

7-A Closer Look at Classes and Methods-2

The document discusses recursion in Java. Recursion is when a method calls itself. A recursive method must have a base case to stop the recursion. The document provides an example Factorial class with a recursive fact method that calculates factorials. It calls itself with decreasing values of n until the base case of n == 1 is reached. The main method calls the fact method on instances of Factorial to calculate 3!, 4!, and 5!.

Uploaded by

aakarsh204
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/ 30

A Closer Look at

Methods and Classes-II


Recursion
• Java supports recursion. Recursion is the process of defining something in
terms of itself. As it relates to Java programming, recursion is the attribute that
allows a method to call itself. A method that calls itself is said to be recursive.
// A simple example of recursion.
class Factorial {
// this is a recursive function
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
• Recursion
• Access Control
• static keyword
• final keyword
• Arrays
• Nested and Inner Classes
• String Class and command line args
• Variable number of args
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
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.
• Java’s access specifiers are public, private, and
protected. Java also defines a default access
level. protected applies only when inheritance
is involved.(protected and private protected)
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
static keyword
• When a member is declared static, it can be accessed
before any objects of its class are created, and without
reference to any object. We can declare both methods
and variables to be static. The most common example
of a static member is main( ). main( ) is declared as
static because it must be called before any objects
exist.
• 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:
1. They can only call other static methods.(without using any
object.)
*[With ‘object.methodname’ they can call non- static method,
like we do in main() which is static. But in general static
method are created to access them without using any object.]
2. They must only access static data.
3. They cannot refer to ‘this’ or ‘super’ in any way.
(The keyword ‘this’ is used to refer to current
instance/object while the keyword ‘super’ is related to
inheritance.(refer to super/base class.))
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void math(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static { //the static block. It will be exe. automatically and will exe. only
once.
System.out.println("Static block initialized."); O/p-> Static block initialized.
b = a * 4; x = 42
a=3
} b = 12
public static void main(String args[]) {
math(42);
}}
• If we need to do computation in order to initialize
our static variables, we can declare a static block
which gets executed exactly once, when the class
is first loaded.
• As soon as the UseStatic class is loaded, all of the
static statement runs. First, a is set to 3, then the
static block executes (printing a message), and
finally, b is initialized to a * 4 or 12.
• Then main( ) is called, which calls meth( ), passing
42 to x. The three println( ) statements refer to the
two static variables a and b, as well as to the local
variable x.
• It is illegal to refer to any instance variables inside
of a static method.
• if we wish to call a static method from outside its
class, we can do so using the following general
form: classname.method( )
• Here, classname is the name of the class in which
the static method is declared. A static variable can
be accessed in the same way—by use of the dot
operator on the name of the class. This is how Java
implements a controlled version of global methods
and global variables.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
Output of this program:
System.out.println("b = " + StaticDemo.b);
a = 42
} b = 99

}
public class Number_Objects
{
static int count=0;
Number_Objects()
{
count++;
}
public static void main(String[] args)
{
Number_Objects obj1 = new Number_Objects();
Number_Objects obj2 = new Number_Objects();
Number_Objects obj3 = new Number_Objects();
Number_Objects obj4 = new Number_Objects();
System.out.println("Number of objects created:"+count);
}
}
Final keyword
• A variable can be declared as final. Doing so prevents its contents
from being modified. This means that we must initialize a final
variable when it is declared. (In this usage, final is similar to const in
C/C++.)
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
• Variables declared as final do not occupy memory on a per- instance
basis. (final variable uses single memory location which is shared by
all instance/objects.). So a final variable is essentially a constant.
• The keyword final can also be applied to methods, but its meaning is
substantially different than when it is applied to variables. (related
with inheritance.)
Arrays
• Array are implemented as objects. Because of
this, there is a special array attribute that we
can take advantage of. Specifically, the size of
an array—that is, the number of elements that
an array can hold—is found in its length
instance variable. All arrays have this variable,
and it will always hold the size of the array.
// This program demonstrates the length array member.
class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
This program displays the following output:
length of a1 is 10
length of a2 is 8
length of a3 is 4
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 is known to A, but not outside 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.
[Inner class can access all members of outer class but
outer class can’t access member of inner class.]
• There are two types of nested classes:
static and non-static.
• A static nested class is one which has the static modifier
applied. Because it is static, it must access the members
of its enclosing class through an object. That is, it cannot
refer to 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. Thus, an
inner class is fully within the scope of its enclosing class.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
} } }
class InnerClassDemo {
public static void main(String args[]) { //Output :
Outer outer = new Outer(); //display: outer_x = 100
outer.test();
} }
• In the program, an inner class named Inner is defined within
the scope of class Outer. Therefore, any code in class Inner can
directly access the variable outer_x.
• An instance method named display( ) is defined inside Inner.
This method displays outer_x on the standard output stream.
• The main( ) method of InnerClassDemo creates an instance of
class Outer and invokes its test( ) method. That method creates
an instance of class Inner and the display( ) method is called.
• class Inner is known only within the scope of class Outer.
• The Java compiler generates an error message if any code
outside of class Outer attempts to instantiate class Inner.
• Generalizing, a nested class is no different than any other
program element: it is known only within its enclosing
scope.
• An inner class has access to all of the members of its
enclosing class, but the reverse is not true.
• Members of the inner class are known only within the
scope of the inner class and may not be used by the outer
class.
*Nested classes were not allowed by the original 1.0
specification for Java. They were added by Java 1.1.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = " + outer_x);
} }
void showy() {
System.out.println(y); // error, y not known here!
} }
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}}
The String Class
• Every string you create is actually an object of type String.
Even string constants are actually String objects. For example,
in the statement
System.out.println("This is a String, too");
the string “This is a String, too” is a String constant.
Fortunately, Java handles String constants in the same way
that other computer languages handle “normal” strings.
• The second thing to understand about strings is that objects
of type String are immutable; once a String object is created,
its contents cannot be altered. While this may seem like a
serious restriction, it is not, for two reasons:
1. If you need to change a string, you can always create a new
one that contains the modifications.
2. Java defines a peer class of String, called StringBuffer, which
allows strings to be altered, so all of the normal string
manipulations are still available in Java.
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
The output produced by this program is shown
here:
} First String
Second String
} First String and Second String
Some methods in string class
• s1. charAt(n);
• s2=s1.toLowerCase();
• s2=s1.toUpperCase();
• s2=s1.replace(‘x’,’y’);
• s2=s1.trim();
• s1.equals(s2);
• s1.equalsIgnoreCase(s2);
• s1.length();
• s1.compareTo(s2);
• s1.concat(s2);
• s1.substring(n);
• s1.substring(n,m);
• s1.indexOf(‘x’);
String and command line args
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
Execute the code by --->>java CommandLine this is a test 100 -1
output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
Variable number of arguments
• Beginning with JDK 5,(v1.5), java has included a
feature to take variable number of arguments.
• A sample method is
void vaTest(int …v);
which can take any number of integer type
arguments. The method can be overloaded for
other types as well. Here v is implicitly declared as
an array without specifying its size.
class A
{
static void vatest(int ...v)
{
System.out.print("Number of args:" + v.length + " contents: ");
for(int x : v)
System.out.print(x+" ");

System.out.println();
}
public static void main(String args[])
{
vatest(10);
vatest(1,2,3);
vatest();
}
}

You might also like