Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×

Object oriented programming in java

Próximo SlideShare
OOP java
OOP java
Cargando en…3

Eche un vistazo a continuación

1 de 38 Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a Object oriented programming in java (20)


Más reciente (20)


Object oriented programming in java

  1. 1. Object-Oriented Programming in Java Elizabeth Alexander Hindustan University
  2. 2. JAVA- OBJECTS & CLASSES ● Java is an Object-Oriented Language. ● Java supports the following fundamental concepts: ■ Polymorphism ■ Inheritance ■ Encapsulation ■ Abstraction ■ Classes ■ Objects ■ Instance ■ Method ■ Message Passing
  3. 3. JAVA OBJECTS & CLASSES ● Object − Objects have states and behaviors ● Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support. The General Form of a Class class classname { type instance-variable1; type instance-variable2; // … type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // … type methodnameN(parameter-list) { // body of method } }
  4. 4. JAVA CLASS A class can contain any of the following variable types. ● Local variables − Variables defined inside methods, constructors or blocks are called local variables. ● The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. ● Instance variables − Instance variables are variables within a class but outside any method. ● These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. ● Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
  5. 5. CREATING AN OBJECT There are three steps when creating an object from a class − ● Declaration − A variable declaration with a variable name with an object type. ● Instantiation − The 'new' keyword is used to create the object. ● Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
  6. 6. DEFINING METHODS The general form of a method: type name(parameter-list) { // body of method } ● type specifies the type of data returned by the method ● The name of the method is specified by name. This can be any legal identifier ● The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. ● If the method has no parameters, then the parameter list will be empty.
  7. 7. ACCESSING INSTANCE VARIABLES AND METHODS ● Instance variables and methods are accessed via created objects. /* First create an object */ ObjectReference = new Constructor(); /* Now call a variable as follows */ ObjectReference.variableName; /* Now you can call a class method as follows */ ObjectReference.MethodName();
  8. 8. INITIALIZING OBJECT IN JAVA ● There are 3 ways to initialize object in java. 1. By reference variable 2. By method 3. By constructor 1. Initialization through reference ● Initializing object simply means storing data into object ● Multiple objects can be created and store information in it through reference variable. 2.Initialization through method ● initializing the objects by invoking the method
  10. 10. DIFFERENT WAYS TO CREATE AN OBJECT IN JAVA There are many ways to create an object in java. They are: ● By new keyword ● By newInstance() method ● By clone() method ● By deserialization ● By factory method etc. Anonymous object ● Anonymous simply means nameless. ● An object which has no reference is known as anonymous object. ● It can be used at the time of object creation only. ● If you have to use an object only once, anonymous object is a good approach
  11. 11. Anonymous object ● Example: new Calculation();//anonymous object ● Calling method through reference: Calculation c=new Calculation(); c.fact(5); ● Calling method through anonymous object new Calculation().fact(5); Creating multiple objects by one type only ● We can create multiple objects by one type only as we do in case of primitives. ● Initialization of primitive variables: int a=10, b=20; ● Initialization of refernce variables: Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects CREATING OBJECTS
  12. 12. CONSTRUCTORS ● Every class has a constructor. ● If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. ● Each time a new object is created, at least one constructor will be invoked. ● The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
  13. 13. OOP PRINCIPLES Encapsulation ● Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse ● Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. ● In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. To achieve encapsulation in Java − ● Declare the variables of a class as private. ● Provide public setter and getter methods to modify and view the variables values.
  14. 14. INHERITANCE ● Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. ● The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). extends Keyword ● extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. Syntax class Super { ..... ..... } class Sub extends Super { ..... ..... }
  15. 15. POLYMORPHISM ● Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
  16. 16. THE JAVA CLASS LIBRARY ● The Java Class Library (JCL) is a set of dynamically loadable libraries that Java applications can call at run time. ● Because the Java Platform is not dependent on a specific operating system, applications cannot rely on any of the platform-native libraries. ● Instead, the Java Platform provides a comprehensive set of standard class libraries, containing the functions common to modern operating systems. ● The Java environment relies on several built-in class libraries that contain many built-in methods that provide support for such things as I/O, string handling, networking,and graphics. ● The standard classes also provide support for windowed output. Thus, Java as a totality is a combination of the Java language itself, plus its standard classes ● Two of Java’s built-in methods: println( ) are members of the System class,which is a class predefined by Java that is automatically included in your programs
  17. 17. “this” KEYWORD ● A method will need to refer to the object that invoked it. ● “This” can be use inside any method to refer to current object. ● “This” is always reference to the object on which the method was invoked. ● this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. ● Using this you can refer the members of a class such as constructors, variables and methods. Note: The keyword this is used only within instance methods or constructors
  18. 18. “this” KEYWORD Cont... In general, the keyword this is used to − ● Differentiate the instance variables from local variables if they have same names, within a constructor or a method. Example: class Student { int age; Student(int age) { this.age = age; } }
  19. 19. “this” KEYWORD Cont... ● Call one type of constructor (parameterized constructor or default) from other in a class. It is known as explicit constructor invocation. Example class Student { int age Student() { this(20); } Student(int age) { this.age = age; } }
  20. 20. AUTOMATIC GARBAGE COLLECTION ● The garbage collector is a program which runs on the Java Virtual Machine which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management. ● In java, garbage means unreferenced objects. ● Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. ● To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management. Advantage of Garbage Collection ● It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory. ● It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
  21. 21. AUTOMATIC GARBAGE COLLECTION Cont... How can an object be unreferenced? There are many ways: ● By nulling the reference ● By assigning a reference to another ● By annonymous object etc. 1) By nulling a reference: Employee e=new Employee(); e=null; 2) By assigning a reference to another: Employee e1=new Employee(); Employee e2=new Employee(); e1=e2;//now the first object referred by e1 is available for garbage collection 3) By annonymous object: new Employee();
  22. 22. The finalize( ) Method ● Sometimes an object will need to perform some action when it is destroyed. ● To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector ● To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. ● Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed. ● The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed,the Java run time calls the finalize( ) method on the object.
  23. 23. The finalize( ) Method Cont... ● The finalize( ) method has this general form: protected void finalize( ) { // finalization code here } ● Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class ● finalize( ) is only called just prior to garbage collection. ● It is not called when an object goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed. Therefore, your program should provide other means of releasing system resources, etc., used by the object. ● It must not rely on finalize( ) for normal program operation.
  24. 24. gc() METHOD ● The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes. public static void gc(){} Note: ● The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
  25. 25. Java - Arrays ● Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. Array is a collection of variables of the same type. ● Instead of declaring individual variables, such as number0, number1, ..., and number99, one array variable can be declared such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. One-Dimensional Arrays Declaring Array Variables dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way.
  26. 26. Java - Arrays Cont... Creating Arrays Syntax: arrayRefVar = new dataType[arraySize]; The above statement does two things − ● It creates an array using new dataType[arraySize]. ● It assigns the reference of the newly created array to the variable arrayRefVar. dataType[] arrayRefVar = new dataType[arraySize]; ● Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement Alternatively you can create arrays as follows − dataType[] arrayRefVar = {value0, value1, ..., valuek}; ● The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
  27. 27. Example double[] myList = new double[10]; Java - Arrays Cont...
  28. 28. Returning an Array from a Method ● A method may also return an array. Multidimensional Arrays ● In Java, multidimensional arrays are actually arrays of arrays ● To declare a multidimensional array variable, specify each additional index using another set of square brackets ■ int twoD[][] = new int[4][5]; Arrays of Characters ● Char arrays. Strings are immutable: they cannot be changed in place or added to. With char arrays, we manipulate character buffers. ● Performance advantages. Char arrays are faster—we can change text data without allocations. With the String constructor, we can convert back into a string. Java - Arrays Cont...
  29. 29. Java - Arrays Cont... Processing Arrays ● When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of same type and size of the array is known The foreach Loops ● JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. Passing Arrays to Methods ● Just as you can pass primitive type values to methods, you can also pass arrays to methods.
  30. 30. Java - Strings Class ● Strings, which are widely used in Java programming, are a sequence of characters ● Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. Creating Strings
  31. 31. CharSequence Interface ● The CharSequence interface is used to represent sequence of characters. It is implemented by String, StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3 classes. Java - Strings Class Cont...
  32. 32. ● The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder classes. What is String in java ● Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.String class is used to create string object. How to create String object? There are two ways to create String object: 1. By string literal 2. By new keyword Java - Strings Class Cont...
  33. 33. 1) String Literal ● Java String literal is created by using double quotes String s="welcome"; ● Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. String s1="Welcome"; String s2="Welcome";//will not create new instance Java - Strings Class Cont...
  34. 34. Java - Strings Class Cont...
  35. 35. Java - Strings Class Cont... ● In the above example only one object will be created. ● Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. ● After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance. Why java uses concept of string literal? ● To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
  36. 36. 2) By new keyword ● String s=new String("Welcome");//creates two objects and one reference variable ● In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool). Java String class methods ● The java.lang.String class provides many useful methods to perform operations on sequence of char values. Java - Strings Class Cont...
  37. 37. Java StringBuffer class ● Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed. Important Constructors of StringBuffer class 1. StringBuffer() :creates an empty string buffer with the initial capacity of 16. 2. StringBuffer(String str) :creates a string buffer with the specified string. 3. StringBuffer(int capacity) :creates an empty string buffer with the specified capacity as length. What is mutable string ● A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.
  38. 38. Java StringBuilder Class ● The java.lang.StringBuilder class is mutable sequence of characters. This provides an API compatible with StringBuffer, but with no guarantee of synchronization. Class constructors ● StringBuilder() : This constructs a string builder with no characters in it and an initial capacity of 16 characters. ● StringBuilder(CharSequence seq) : This constructs a string builder that contains the same characters as the specified CharSequence. ● StringBuilder(int capacity) : This constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. ● StringBuilder(String str) : This constructs a string builder initialized to the contents of the specified string