Sie sind auf Seite 1von 43

BITS Pilani

BITS Pilani
Hyderabad Campus

Dr.Aruna Malapati Asst Professor Department of CSIS

BITS Pilani
Hyderabad Campus

OBJECT ORIENTED PROGRAMMING Methods and classes

Todays Agenda
Methods Argument passing Recursion Access Control Understanding static and final Arrays

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Overloading methods
In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java. Javas polymorphism. Java uses the type and / or number of arguments as its guide to determine which version of the methods to be used. Overloaded methods
Method names are same. Differ in type and / or number of parameters. Return type may or may not be same. (this alone is not enough)

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Type conversion in method overloading


If java does not find a method with same type of parameter but number of arguments are same then it goes for type casting.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Overloaded constructors
class Box { double width; double height; double depth; double volume() { return (width *height*depth); } Box() { System.out.println("object created with no dimensions"); width=-1; height=-1; depth=-1; } Box(double w,double h,double d) { System.out.println("object created with parameters passed"); width=w; height=h; depth=d; } Box(double len) { width = height = depth = len; } }

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Using objects as parameters


You can also pass objects as parameters. One of the most common uses of object parameters involves constructors. Frequently you will want to construct a new object so that it is initially the same as some existing object. To do this, you must define a constructor that takes an object of its class as a parameter.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Argument passing
Call by value : when you pass a simple type to a method, it is call by value. Call by reference: Objects are passed by reference

Methods can also return objects.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Recursion
Java supports recursion.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Access control
Encapsulation links data with code that manipulates it. Encapsulation allows you to control what parts of the program can access members of a class. Used to prevent misuse.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Access Specifiers
Access Specifier defines the boundary and scope to access the method, variable and class etc. Java has define four type of access specifier such as: public private protected default

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

public specifiers
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as public can be accessed from any class in the Java program, whether these classes are in the same package or in another package. public class Demo // public class { public x, y, size; // public instance variables }

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Source file declaration rules


Rule 1: public class name and program name should be same. Rule 2: Only one public class is allowed in a .java file.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Private Specifier
Private Specifiers achieves the lowest level of accessibility. Private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Private Specifier
public class Demo { // public class private double x, y; // private (encapsulated) instance v ariables public set(int x, int y) { // setting values of private fields this.x = x; this.y = y; } public get() { // setting values of private fields return Point(x, y); } }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Protected Specifier
Methods and fields declared as protected can only be accessed by the subclasses in other package or any class within the package of the protected members' class. The protected access specifier cannot be applied to class and interfaces.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Default specifier
When you don't set access specifier for the element, it will follow the default accessibility level. Classes, variables, and methods can be default accessed. Using default specifier we can access class, method, or field which belongs to same package, but not from outside this package.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Source file declaration rules


Rule : Any number of Default classes are allowed in a single .java file with any filename.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Access Specifiers
The four access levels are: Visible to the package. the default. No modifiers are needed. Visible to the class only (private). Visible to the world (public). Visible to the package and all subclasses (protected).

The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
public class Customer { private String email; String position; //no modifier = package access modifier protected String name; public String city; }

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Static keyword
Static keyword can be used with variables, methods and block of code. It is a variable which belongs to the class and not to object(instance) Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables A single copy to be shared by all instances of the class A static variable can be accessed directly by the class name and doesnt need any object Syntax : <class-name>.<variable-name>
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

static method
It is a method which belongs to the class and not to the object(instance) A static method can access only static data. It can not access non-static data (instance variables) A static method can call only other static methods and can not call a non-static method from it. A static method can be accessed directly by the class name and doesnt need any object Syntax : <class-name>.<method-name> A static method cannot refer to this or super keywords in anyway.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Static block
Static keyword can be applied to a block, { }, and they become static initialization block which runs only once when the class is first loaded by the JVM. This is used for initializing all the static variables and to perform any operations need to be executed when the class is loaded. They dont return anything. They dont take any arguments. They are executed in the order in which they appear in the class, i.e.) from top to bottom

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Final
Final in java is very important keyword and can be applied to class, method, and variables in Java. Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. Example final int hoursInDay=24;

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Arrays
Using and array in your program is a 3 step process 1) Declaring your Array int[ ] aryNums; 2) Constructing your Array aryNums = new int[6]; 3) Initializing your Array aryNums[0] = 10; int[ ] aryNums = { 1, 2, 3, 4 }; String[ ] aryStrings = {"Autumn", "Spring", "Summer", "Winter" }; boolean[ ] aryBools = new boolean[ ] {false, true, false, true};
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Passing arrays by reference


Arrays are passed to functions by reference, or as a pointer to the original.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Multidimensional Arrays
Ex: int twoD[ ][ ] = new int[4][5] ; When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Steps during object creation


Object creation is a four step process. Create memory for all instance variables. Assign default values to those instance variables. Call the constructor(Implicit / Explicit ). Return the memory references.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Array of objects
It is possible to declare array of reference variables. Class = new Class[array_length] Account obj[] = new Account[2]

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

For loop and arrays

double[] ar = {1.2, 3.0, 0.8}; int sum = 0; for (double d : ar) { // d gets successively each value in ar. sum += d; } double[] ar = {1.2, 3.0, 0.8}; int sum = 0; for (int i = 0; i < ar.length; i++) { // i indexes each element successively. sum += ar[i]; }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Nested and inner classes


Classes that are declared inside the body of a class are called "nested classes". The following are the main reasons behind the concept of nested classes in Java:
Grouping of logical classes When designing a class, we always try to create well-focused classes - with a unique behavior and purpose. Let us imagine we have designed classes A and B on the same principle. Later we found, class B can only be used by class A. In such cases, we can simply put class B inside class A. Encapsulation By writing nested classes, we have hidden them from the world and made them available only to their enclosing class. Maintainability and re-usability of code Encapsulation brings the beauty of maintainability of code. In our earlier example, we can write another class B which is visible to the entire world. This has nothing to do with the one already present inside class A.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Nested and inner classes


Nested class is of 2 kinds:
Non-Static Inner class Static nested class

Inner class is of 3 types:


Inner class Method-local inner class Anonymous inner class

Nested class behaves just like any other member of its enclosing(outer) class. It has access to all the members of its enclosing class.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Nested and inner classes

class A { class B { } }

Has access to all members including private

Class A cannot access members in Class B


CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Inner Class
We define the term "inner class" to the nested class that is:
declared inside the body of another class. not declared inside a method of another class. not a static nested class. not an anonymous inner class.

Example class Outer{ class Inner{ } }

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

static inner class (Static member class)


A static member class behaves much like an ordinary top-level class, except that it can access the static members of the class that contains it. The static nested class can be accessed as the other static members of the enclosing class without having an instance of the outer class. The static class can contain non-static and static members and methods.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
public class InnerClass { static class StaticInner { static int i = 9; int no = 6; private void method() {} public void method1() {} static void method2() {} final void method3() {} } } The static inner class can be accessed from Outer Class in the following manner: InnerClass.StaticInner staticObj= new InnerClass. StaticInner (); No outer class instance is required to instantiate the nested static class because the static class is a static member of the enclosing class.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Non static inner classes


Non - static inner classes classes associated with the object of the enclosing class. Member class - Classes declared outside a function (hence a "member") and not declared "static". The member class can be declared as public, private, protected, final and abstract. public class InnerClass { class MemberClass { public void method1() { } } }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Instantiating an Inner Class


Since inner class can't stand on its own, we need an instance of its outer class to tie it. There are 2 ways to instantiate an instance of inner class:
From within its outer class (example InstantiateInner.java) From outside its outer class (example InstantiateInner2.java)

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Modifier applied to inner class


Following are modifiers that can be applied to the inner: public private abstract final protected strictfp static turns the inner class into static nested class.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Method local class


The inner class declared inside the method is called method local inner class. Method local inner class can only be declared as final or abstract. Method local class can only access global variables or method local variables if declared as final.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
public class InnerClass { int i = 9; public void method1() { final int k = 6; class MethodLocal { MethodLocal() { System.out.println(k + i); } } } }

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Anonymous inner class


These are local classes which are automatically declared and instantiated in the middle of an expression. Also, like local classes, anonymous classes cannot be public, private, protected, or static. They can specify arguments to the constructor of the superclass, but cannot otherwise have a constructor. Anonymous class cannot define any static fields, methods, or classes, except for static final constants. Also, like local classes, anonymous classes cannot be public, private, protected, or static

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Summary
Methods provide functionality to the class and use the class data. Methods can be overloaded only if the number of parameters are different. Methods can be static and can access only static variables. Access specifiers add encapsulation to the class, methods or instance variables. Inner class is enclosed in the scope of outer class.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Das könnte Ihnen auch gefallen