java and oops

Upload: tinynith

Post on 02-Jun-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 Java and OOPS

    1/10

    Object-oriented programming (OOP): It is a programming paradigm that representsconcepts as "objects" that have data fields( attributes that describe the object) and associated

    procedures known as methods. Objects, which are usually instances of classes, are used tointeract with one another to design applications and computer programs.

    OOPs view a program as a collection of loosely connected objects. Each object is responsiblefor a specific task.

    Characteristics of oops :

    1) Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchicalclassification. Creating new class is also known as the derived class. The concept ofinheritance provides an important feature to the object-oriented language - reusability.A programmer can take an existing class and, without modifying it, and additional

    features and capabilities to it.Method overriding , in object oriented programming, is a language feature that allowsa subclass or child class to provide a specific implementation of a method that isalready provided by one of its super classes or parent classes. The implementation inthe subclass overrides (replaces) the implementation in the super class by providing amethod that has same name, same parameters or signature, and same return type as themethod in the parent class .[1] The version of a method that is executed will bedetermined by the object that is used to invoke it. If an object of a parent class is usedto invoke the method, then the version in the parent class will be executed, but if an

    object of the subclass is used to invoke the method, then the version in the child classwill be executed. Some languages allow a programmer to prevent a method from beingoverridden.

    2) Encapsulation:

    Encapsulation is a programming mechanism that binds together code and the data itmanipulates, and that keeps both safe from outside interference and misuse. In anobject-oriented language, code and data can be bound together in such a way that a self-contained black box is created. Within the box are all necessary data and code. Whencode and data are linked together in this fashion, an object is created. In other words, anobject is the device that supports encapsulation.Within an object, code, data, or both may be private to that object or public . Privatecode or data is known to and accessible by only another part of the object. That is,

    private code or data cannot be accessed by a piece of the program that exists outside theobject. When code or data is public, other parts of your program can access it eventhough it is defined within an object. Typically, the public parts of an object are used to

    provide a controlled interface to the private elements of the object.Javas basic unit of encapsulation is the class . A class defines the form of an object. Itspecifies both the data and the code that will operate on that data. Java uses a classspecification to construct objects . Objects are instances of a class. Thus, a class is

    essentially a set of plans that specify how to build an object. The code and data thatconstitute a class are called members of the class. Specifically, the data defined by the

    http://en.wikipedia.org/wiki/Programming_paradigmhttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Field_(computer_science)http://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Instance_(computer_science)http://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Object_oriented_programminghttp://en.wikipedia.org/wiki/Subclass_(computer_science)http://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Superclass_(computer_science)http://en.wikipedia.org/wiki/Parameter_(computer_science)http://en.wikipedia.org/wiki/Method_overriding#cite_note-flanagan-1http://en.wikipedia.org/wiki/Method_overriding#cite_note-flanagan-1http://en.wikipedia.org/wiki/Method_overriding#cite_note-flanagan-1http://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Programmerhttp://en.wikipedia.org/wiki/Programmerhttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Method_overriding#cite_note-flanagan-1http://en.wikipedia.org/wiki/Parameter_(computer_science)http://en.wikipedia.org/wiki/Superclass_(computer_science)http://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Subclass_(computer_science)http://en.wikipedia.org/wiki/Object_oriented_programminghttp://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Instance_(computer_science)http://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Field_(computer_science)http://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Programming_paradigm
  • 8/11/2019 Java and OOPS

    2/10

    class are referred to as member variables or instance variables. The code that operateson that data is referred to as member methods or just methods. Method is Javas term fora subroutine. If you are familiar with C/C++, it may help to know that what a Java

    programmer calls a method, a C/C++ programmer calls a function.

    3) Polymorphism:The concept of polymorphism is often expressed by the phrase one interface, multiplemethods. This means that it is possible to design a generic interface to a group ofrelated activities. Polymorphism helps reduce complexity by allowing the sameinterface to be used to specify a general class of action .Polymorphism is an object oriented programming concept to refer to the ability of avariable, function, or object to take on multiple forms. A language that features

    polymorphism allows developers to program in the general rather than program in thespecific.

    4) Abstraction: Abstraction takes many specific instances of objects and extracts theircommon information and functions to create a single generalized concept that can beused to describe all the specific instances as one. Abstraction is essential in theconstruction of programs. It places the emphasis on what an object is or does rather thanhow it is represented or how it works. Thus, it is the primary means of managingcomplexity in large programs.

    Byte code- portable code

    Difference between structured programming and object oriented programming:

    In the most general sense, a program can be organized in one of two ways: around its code(what is happening) or around its data (what is being affected). Using only structured

    programming techniques, programs are typically organized around code. This approach can be thought of as code acting on data.

    Object-oriented programs work the other way around. They are organized around data, withthe key principle being data controlling access to code. In an objec t-oriented language, youdefine the data and the routines that are permitted to act on that data. Thus, a data typedefines precisely what sort of operations can be applied to that data.

    TRY CATCH, Exception handling

    http://www.youtube.com/watch?v=K_-3OLkXkzY

    ParseInt converts string to integer

    Compilation and Running

    http://www.youtube.com/watch?v=K_-3OLkXkzYhttp://www.youtube.com/watch?v=K_-3OLkXkzYhttp://www.youtube.com/watch?v=K_-3OLkXkzY
  • 8/11/2019 Java and OOPS

    3/10

    Random Number Generator:

    eturns a double value with a positive sign, greater than or equal to 0.0 and lessthan 1.0

    to convert into int:

    int a = (int) (Math. random () * first.length);

    Integer is needed.

    Object: has

    1) Instance Variables: State, knows, Song has title, artist2) Methods: Behavior, does, Song can be played

    Instance variablesInstance variables are any variables, without "static" field modifier, that are defined withinthe class body and outside any class's methods body .Instance variables are in scope as long as their enclosing object is in scope. An instancevariable is a part of the object that contains it and cannot live independently of it.All object instances have their own copies of instance variables. One object instance canchange values of its instance variables without affecting all other instances.Instance variables can be used by all methods of a class unless the methods are marked with"static" modifier. You access instance variables directly from their containing objectinstances.

    JVM/Virtual machine

    runs .class file output

    Compilation

    runs javac generates .class file made up of bytecode

    Sources Code (.java)

    (whatever code we write)

  • 8/11/2019 Java and OOPS

    4/10

    * Marking a method as public and static makes it like a global method. Any code in any classof your application can access a public static method. If you mark a variable as public s tatic and final, you have successfully created a globally available constant.

    Arguments: Values sent to a method by a calling codeReturn types: values sent back to the caller/invoker of the method

    The array is an object even though its an array of primitive variables/object referencevariables

    Running a method from main method:When return is expected: result = my_class.even_odd(a);Where result is the variable where return value will be stored. When return is not expected: my_class.even_odd(a);

    A class contains constructors that are invoked to create objects from the class blueprint.Constructor declarations look like method declarations except that they use the name of theclass and have no return type.

    Instance variables are declared inside a class but not within a method. Local variables aredeclared within a method. Local variables do NOT get a default value! The compilercomplains if you try to use a local variable before the variable is initialized.

    Constructor:

    Constructors have one purpose in life: to create an instance of a class. This can also be calledcreating an object, as in:

    Platypus p1 = new Platypus();

    The purpose of methods, by contrast, is much more general. A method's basic function is toexecute Java code.Signature differences

    Constructors and methods differ in three aspects of the signature: modifiers, return type, andname. Like methods, constructors can have any of the access modifiers: public, protected,

    private, or none (often called package or friendly ). Unlike methods, constructors can takeonly access modifiers. Therefore, constructors cannot be abstract, final, native, static,or synchronized.

    The return types are very different too. Methods can have any valid return type, or no return

    type, in which case the return type is given as void. Constructors have no return type, noteven void.

  • 8/11/2019 Java and OOPS

    5/10

    Finally, in terms of the signature, methods and constructors have different names.Constructors have the same name as their class; by convention, methods use names other thanthe class name. If the Java program follows normal conventions, methods will start with alowercase letter, constructors with an uppercase letter. Also, constructor names are usually

    nouns because class names are usually nouns; method names usually indicate actions.This:

    When instance variables and variable inside a method have same name, method always usesinstance variables. If we want the method to use method variables, we can use this.

    String input scan:

    string1=scan.nextLine(); If you want complete line. i/p- I am kusum. Result- I am kusum.

    string1=scan.next(); only before 1 st space. i/p This is amazing. Result: this

    Method overloading: In Java, two or more methods within the same class can share thesame name, as long as their parameter declarations are different. When this is the case, themethods are said to be overloaded, and the process is referred to as method overloading.Method overloading is one of the ways that Java implements polymorphism. One important restriction: the type and/or number of the parameters of each overloadedmethod must differ.

    Abstract Super class: you can always assign a subclass object to a super class referenceeven if the super class is abstract. Abstract class means it cannot be instantiated. Opposite ofan abstract class is a concrete class which can be instantiated.

    Objects: Live on garbage collectible heap

    Variables:

    a) Instance variables: declared inside a class but not inside a method

    b) Local variables: local variables are declared inside a method. Live on Stack (also knownas stack variables) method invocations also live in stack dostuff(). Local variables aretemporary and live as long as the method has not reached closing curly brace.

    Static: static methods run without knowing about any particular instance of the static methodclass .http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html Both methods and variables can be static. Variables declared as static are, essentially, globalvariables. When an object is declared, no copy of a static variable is made. Instead, allinstances of the class share the same static variable.

    Static/class variable calling : class.variable or object.variable

    http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.htmlhttp://docs.oracle.com/javase/tutorial/java/javaOO/classvars.htmlhttp://docs.oracle.com/javase/tutorial/java/javaOO/classvars.htmlhttp://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
  • 8/11/2019 Java and OOPS

    6/10

    Instance variable calling = object.variable

    Static and Normal method: The difference between a static method and a normal method isthat the static method can be called through its class name, without any object of that class

    being created.

    Methods declared as static have several restrictions:

    They can call only other static methods.

    They must access only static data.

    They do not have a this reference.

    Nullpointerexception: using . (dot) on a null reference

    The following table shows the access to members permitted by each modifier.

    Access LevelsModifier Class Package Subclass Worldpublic Y Y Y Yprotected Y Y Y N

    Default Y Y N Nprivate Y N N N

    toString() In Java

    The toString() method solves so many question that we see these days in the forums,and it is crucially important to understand it. It is a method that is defined in the Object

    class and thus, every object has one, however, it prints out, for the most part,meaningless information. Let me show you an example. Im going to write a simple classthat stores the name and age of somebody:

    01 public class Person { 02

    03 private int age; 04 private String name; 05

    06 public Person() {

  • 8/11/2019 Java and OOPS

    7/10

    07 this (0, ""); 08 } 09 10

    11 public Person(int i, String string) { 12 age = i; 13 name = string; 14 } 15 16

    17 public static void main(String[] args) { 18 Person p = new Person(40, "John Doe"); 19 System.out.println(p);

    20 } 21 }

    This program prints p as Person@3e25a5 which is the default implementation oftoString(). This output is the class name (Person) and the hash code that represents thatobject. This is because under the covers System.out.println() calls an objects toString()method implicitly.However, this output is virtually meaningless. No end user wants to know what the class

    name or the hash code is. They want to know what the object IS. In that case, they willwant to know the age and name of the Person object that they have. You only have tomake one change add a toString() method to whatever class that you want todescribe. Following is an improved version of the above program with a toString()method added:

    01 public class Person { 02

    03 private int age; 04 private String name; 05 06 public Person() { 07 this (0, ""); 08 } 09 10

    11 public Person(int i, String string) { 12 age = i;

    13 name = string; 14 }

  • 8/11/2019 Java and OOPS

    8/10

    15 16 @Override 17 public String toString() { 18 return "Name: " + name + " \nAge: " + age + "\n\n";

    19 } 20

    21 22 public static void main(String[] args) { 23 Person p = new Person(40, "John Doe"); 24 System.out.println(p); 25 } 26 }

    The output here is much nicer. This time it nicely tells the Name and the Age of thePerson:Name: John Doe

    Age: 40

    So, what uses does this have? Loads. If you EVER need a String representation of anyobject for any purpose, toString() is the easiest way to go. It can perform any number ofcomputations as long as it returns a String in the end. This makes it easier for objectsthat have arrays to return their values. It also makes debugging a lot easier and makesyour objects easier to understand. Remember that if you ever need the oldimplementation with the addition of something new, you can alwaysadd super.toString() to the returned String.

    Every class implements toString( ) because it is defined by Object . However, the defaultimplementation of toString( ) is seldom sufficient. For most important classes that you create,

    you will want to override toString( ) and provide your own string representations. Fortunately,this is easy to do. The toString( ) method has this general form:

    String toString( )

    To implement toString( ) , simply return a String object that contains the human-readable stringthat appropriately describes an object of your class.By overriding toString( ) for classes that you create, you allow the resulting strings to be fullyintegrated into Java's programming environment. For example, they can be used in print() and println( ) statements and in concatenation expressions. The following programdemonstrates this by overriding toString( ) for the Box class:

    // Override toString() for Box class.

    class Box {

    double width;

  • 8/11/2019 Java and OOPS

    9/10

    double height;

    double depth;

    Box(double w, double h, double d) {

    width = w;

    height = h;

    depth = d;

    }

    public String toString() {

    return "Dimensions are " + width + " by " +

    depth + " by " + height + ".";

    }

    }

    class toStringDemo {

    public static void main(String args[]) {

    Box b = new Box(10, 12, 14);

    String s = "Box b: " + b; // concatenate Box object

    System.out.println(b); // convert Box to string

    System.out.println(s);

    }

    }

    The output of this program is shown here:

    Dimensions are 10 by 14 by 12.Box b: Dimensions are 10 by 14 by 12.As you can see, Box 's toString( ) method is automatically invoked when a Box object is used in aconcatenation expression or in a call to println( ) .

    Thread: Runnable is to a thread what hob is to a worker. A runnable is the job the thread issupposed to run. A Runnable holds the method that goes on the bottom of the new threadsstack: run().

    Inside run(),you will define the code that constitutes the new thread. It is important tounderstand that run() can call other methods, use other classes, and declare variables just likethe main thread. The only difference is that run() establishes the entry point for another,concurrent thread of execution within your program. This thread will end when run() returns.

    Multithreading Vs Multitasking

    There are two distinct types of multitasking: process-based and thread-based. It is importantto understand the difference between the two. A process is, in essence, a program that isexecuting. Thus, process-based multitasking is the feature that allows your computer to runtwo or more programs concurrently. For example, it is process-based multitasking that allows

  • 8/11/2019 Java and OOPS

    10/10

    you to run the Java compiler at the same time you are using a text editor or browsing theInternet. In process-based multitasking, a program is the smallest unit of code that can bedispatched by the scheduler.

    In a thread-based multitasking environment, the thread is the smallest unit of dispatchable

    code. This means that a single program can perform two or more tasks at once. For instance,

    a text editor can be formatting text at the same time that it is printing, as long as these two

    actions are being performed by two separate threads. Although Java programs make use of

    process-based multitasking environments, process-based multitasking is not under the control

    of Java. Multithreaded multitasking is.

    The principal advantage of multithreading is that it enables you to write very efficient programs because it lets you utilize the idle time that is present in most programs. As you

    probably know, most I/O devices, whether they be network ports, disk drives, or thekeyboard,

    are much slower than the CPU. Thus, a program will often spend a majority of its execution

    time waiting to send or receive information to or from a device. By using multithreading,your

    program can execute another task during this idle time. For example, while one part of your

    program is sending a file over the Internet, another part can be reading keyboard input, and

    still another can be buffering the next block of data to send.