Introduction to java Rupali Sherekar 2017.

1 Introduction to java Rupali Sherekar 2017 ...
Author: Elfreda Bailey
0 downloads 0 Views

1 Introduction to java Rupali Sherekar 2017

2 History Java is a programming language created by James Gosling from Sun Microsystems (Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in 1995. Sun Microsystems was acquired by the Oracle Corporation in Oracle has now the steermanship for Java. Over time new enhanced versions of Java have been released. The current version of Java is Java 1.8 which is also known as Java 8. Rupali Sherekar 2017

3 From the Java programming language the Java platform evolvedFrom the Java programming language the Java platform evolved. The Java platform allows software developers to write program code in other languages than the Java programming language which still runs on the Java virtual machine. The Java platform is usually associated with the Java virtual machine and the Java core libraries. Rupali Sherekar 2017

4 Java Virtual machine The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine. The Java virtual machine is written specifically for a specific operating system, e.g., for Linux a special implementation is required as well as for Windows. Rupali Sherekar 2017

5 JVM Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program. Rupali Sherekar 2017

6 Rupali Sherekar 2017

7 Why? Rupali Sherekar 2017

8 Java Runtime Environment vs. Java Development KitA Java distribution typically comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit(JDK). The Java runtime environment (JRE) consists of the JVM and the Java class libraries. Those contain the necessary functionality to start Java programs. The JDK additionally contains the development tools necessary to create Java programs. The JDK therefore consists of a Java compiler, the Java virtual machine and the Java class libraries. Rupali Sherekar 2017

9 Characteristics of JavaThe target of Java is to write a program once and then run this program on multiple operating systems. Rupali Sherekar 2017

10 Platform independent:A Java program (which is standard-compliant and follows certain rules) can run unmodified on all supported operating systems(platforms), e.g., Windows or Linux. This makes Java programs highly portable. Java programs use the Java virtual machine in between and do not access the operating system directly. Rupali Sherekar 2017

11 Object-orientated programming language:Except the primitive(basic) data types, all elements in Java are objects. Rupali Sherekar 2017

12 Strongly-typed programming language:Java is strongly-typed, e.g., the types of the used variables must be pre-defined and conversion to other datatypes is relatively strict, e.g., must be done in most cases by the programmer. Rupali Sherekar 2017

13 Interpreted and compiled language:Java source code is transferred into the bytecode format which does not depend on the target platform(i.e. the operating system). These bytecode instructions are interpreted by the Java Virtual machine (JVM). The JVM also contains a so called Hotspot-Compiler which translates performance critical bytecode instructions into native code instructions. Rupali Sherekar 2017

14 Automatic memory management:Java manages the memory allocation and de-allocation for creating new objects.(In C++,C ?) The program does not have direct access to the memory. (In C++,C ?) The garbage collector automatically deletes objects to which no active pointer exists(means which is not in use). Rupali Sherekar 2017

15 Development Process with JavaJava source files are written as plain text documents. The programmer typically writes Java source code in an Integrated Development Environment (IDE) for programming. An IDE supports the programmer in the task of writing code, e.g., it provides auto-formating of the source code, highlighting of the important keywords, etc. To compile the program the programmer (or the IDE) calls the Java compiler (javac). The Java compiler converts the sourcecode to the bytecode . These instructions are stored in .class files and can be executed by the Java Virtual Machine Rupali Sherekar 2017

16 Garbage collector The JVM automatically re-collects the memory which is not referred to by other objects. The Java garbage collector checks all object references and finds the objects which can be automatically released. While the garbage collector relieves the programmer from the need to explicitly manage memory, the programmer still need to ensure that he does not keep unneeded object references, otherwise the garbage collector cannot release the associated memory. Keeping unneeded object references are typically called memory leaks. Rupali Sherekar 2017

17 Installation of Java 2.1. Check installationJava might already be installed on your machine. You can test this by opening a console and by typing in the following command: java -version If Java is correctly installed, you should see some information about your Java installation. If the command line returns the information that the program could not be found, you have to install Java. Rupali Sherekar 2017

18  Install Java On Ubuntu you can install Java via the following command on the command line. sudo apt-get install openjdk-7-jdk For Microsofts Windows, Oracle provides a native installer which can be found on the Oracle website. Link Rupali Sherekar 2017

19 Validate installationSwitch again to the command line and run the following command. java -version The output should be similar to the following output. java version "1.7.0_25" OpenJDK Runtime Environment (IcedTea ) (7u ubuntu ) OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode) Rupali Sherekar 2017

20 Write, compile and run a Java programThe following Java program is developed under Linux using a text editor and the command line. Rupali Sherekar 2017

21 Write Select or create a new directory which will be used for your Java development. Open a text editor which supports plain text, e.g., gedit under Linux or Notepad under Windows OR Better option is to open a new text document(in Linux) Rupali Sherekar 2017

22 Screen shot Rupali Sherekar 2017

23 Save and execute Save the source code in your javadir directory with the HelloWorld.java filename. It is good to keep the name of a Java source file similar the class name (within the source code) and end with the .java extension. In this example the filename should be be HelloWorld.java, because the class is called HelloWorld.(Note the case sensitivity) Rupali Sherekar 2017

24 Execute Switch to the javadir directory with the command cd javadir, for example, in the above example via the cd command. Use the ls command (dir under Microsoft Windows) to verify that the source file is in the directory. Rupali Sherekar 2017

25 compile Compile your Java source file into a class file with the following command. javac HelloWorld.java Rupali Sherekar 2017

26 Execute Afterwards list again the content of the directory with the ls or dir command. The directory contains now a fileHelloWorld.class. If you see this file, you have successfully compiled your first Java source code into bytecode. Rupali Sherekar 2017

27 Execute By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag. Rupali Sherekar 2017

28 Execute You can now start your compiled Java program.Ensure that you are still in the jardir directory and enter the following command to start your Java program. java HelloWorld Rupali Sherekar 2017

29 Execute The system should write "Hello World" on the command lineRupali Sherekar 2017

30 EXecute If you are not in the directory in which the compiled class is stored, then the system will show an error message:Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass To use the class, type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output. java -classpath "mydirectory" HelloWorld Rupali Sherekar 2017

31 History Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak,” but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype Rupali Sherekar 2017

32 How Java Changed the InternetJava Applets Security Portability Rupali Sherekar 2017

33 Java’s Magic: The BytecodeThe key that allows Java to solve both the security and the portability problems is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). The original JVM was designed as an interpreter for bytecode. The fact that a Java program is executed by the JVM helps solve the major problems associated with web-based programs. Rupali Sherekar 2017

34 Just-In-Time (JIT) compilerSun began supplying its HotSpot technology not long after Java’s initial release. HotSpot provides a Just-In-Time (JIT) compiler for bytecode. When a JIT compiler is part of the JVM, selected portions of bytecode are compiled into executable code in real time, on a piece-by-piece, demand basis. It is important to understand that it is not practical to compile an entire Java program into executable code all at once, because Java performs various run-time checks that can be done only at run time. Instead, a JIT compiler compiles code as it is needed, during execution. Furthermore, not all sequences of bytecode are compiled—only those that will benefit from compilation. The remaining code is simply interpreted. However, the just-in-time approach still yields a significant performance boost. Even when dynamic compilation is applied to bytecode, the portability and safety features still apply, because the JVM is still in charge of the execution environment. Rupali Sherekar 2017

35 Servlets: Java on the Server SideRupali Sherekar 2017

36 Java Features Simple: as it is syntactically similar to C++ and has the object oriented features of c++ Secure: The JVM restricts the entry of applets to itself. Java achieved this protection by confining an applet to the Java execution environment and not allowing it access to other parts of the computer. Then there is no provision for direct memory access( no pointers) Portable : can run on any operating system. So you can have write once run antwhere code Object-oriented: follows the paradigms of object oriented programming Robust(memory mng,exceptions): has automatic memory management with the garbage collector. Checks and stops many errors from occuring during compile time itself with its exception handling mechanism. Ex arrays Multithreaded: can execute different parts of the same program parallely. Architecture-neutral: write once run anywhere programs are possible due to the JVM High performance : The JVM has a Just in Time compiler. Selected portions of bytecode are compiled into executable code in realTime. Distributed: Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network. Rupali Sherekar 2017

37 list of its major new features:• Generics • Annotations • Autoboxing and auto-unboxing • Enumerations • Enhanced, for-each style for loop • Variable-length arguments (varargs) • Static import • Formatted I/O • Concurrency utilities Rupali Sherekar 2017

38 Data Types (Integers) Rupali Sherekar 2017

39 Data Types (Floats) Rupali Sherekar 2017

40 Data Types (Character and Boolean)char c1=‘d’; occupies 2 bytes boolean x=true Ex boolean Rupali Sherekar 2017

41 Type Conversion and CastingJava’s Automatic Conversions When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: The two types are compatible. The destination type is larger than the source type. When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required. Ex: int x=25, short y=15; x=y; Allowed because conversion from smaller type to larger y=x ;  Not allowed as conversion from larger type to smaller Rupali Sherekar 2017

42 Rupali Sherekar 2017

43 Casting Incompatible Types and from larger to smaller typesTo create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion (target-type) value Ex: int a; byte b; // ... b = (byte) a; If the integer’s value is larger than the range of a byte only the lower bytes will be considered. EX Rupali Sherekar 2017

44 Casting Incompatible TypesThus,when a floating-point value is assigned to an integer type, the fractional component is lost However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other. Rupali Sherekar 2017

45 Arrays The general form of a one-dimensional array declaration istype var-name[ ]; Ex: int arr[]; Actually allocating memory array-var = new type[size]; arr = new int[12]; After this statement executes, arr will refer to an array of 12 integers. Further, all elements in the array will be initialized to zero. OR int arr[]=new int [12]; int [] arr=new int[12]; Rupali Sherekar 2017

46 Arrays Obtaining an array is a two-step process.First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated Rupali Sherekar 2017

47 Initializing array elementsint month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 }; Java strictly checks to make sure you do not accidentally try to store or reference values outside of the range of the array. The Java run-time system will check to be sure that all array indexes are in the correct range. For example, the run-time system will check the value of each index into month_days to make sure that it is between 0 and 11 inclusive. If you try to access elements outside the range of the array (negative numbers or numbers greater than the length of the array), you will cause a run-time error. Rupali Sherekar 2017

48 Home Work Find average of all elements in an arrayFind the largest element in an array Rupali Sherekar 2017

49 Arithmetic operators Rupali Sherekar 2017

50 Bitwise Operators Bitwise operators that can be applied to the integer types, long, int, short,char, and byte. These operators act upon the individual bits of their operands Rupali Sherekar 2017

51 Bit Wise Operators Right Shift -1 Rupali Sherekar 2017

52 Bit Wise Logical OperatorsThe bitwise logical operators are &, |, ^, and ~. Rupali Sherekar 2017

53 Bitwise Operator ExampleEx int a=5 int b=15 int c=a&b; Binary of a=0101 Binary of b= anding both i. e a&b c= 0101 Decimal of 0101 is 5 and so output is 5 Rupali Sherekar 2017

54 Relational Operators The relational operators determine the relationship that one operand has to the other. The outcome of these operations is a boolean value. The relational operators are mostfrequently used in the expressions that control the if statement and the various loop statements. Any type in Java, including integers, floating-point numbers, characters, and Booleans can be compared using the equality test, ==, and the inequality test, !=. Only integer, floating-point, and character operands may be compared to see which is greater or less than the other Result produced by a relational operator is a boolean value Ex: int a = 4; int b = 1; boolean c = a < b; In this case, the result of a Rupali Sherekar 2017

55 Relational Operators Rupali Sherekar 2017

56 Boolean Operators The Boolean logical operators shown here operate only on boolean operands Ex: boolean a = true; boolean b = false; boolean c = a | b; //c=true as one value is true boolean d = a & b; //c =false as one value is true boolean e = a ^ b; // c=true as values of a and b are unequal Rupali Sherekar 2017

57 Boolean Operators Rupali Sherekar 2017

58 Ternary operator exampleexpression1 ? expression2 : expression3 Both expression2 and expression3 are required to return the same type, which can’t be void. EX:Get absolute value of an int variable in another variable int a=5,b=10; a>b? System.out.println(“a is greater”) : System.out.println(“b is greater”); Rupali Sherekar 2017

59 Operator precedence Rupali Sherekar 2017

60 Control Statements Conditional/Branching/SelectionIf and switch Looping/ Iteration/Repetition For,while,do..while, for each loop Jump break,continue Rupali Sherekar 2017

61 Control Statements(conditional/branching and looping)if statements if (condition) statement1; else statement2; Nested ifs if-else-if Ladder if(condition) statement; else if(condition) ... Ex: marks example, seasons example of homework Rupali Sherekar 2017

62 if Statements Month example unit1 prog\Months.java Season ExampleMarks example Rupali Sherekar 2017

63 Switch Statement The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression switch (expression) { case value1: // statement sequence break; case value2: ... case valueN: default: // default statement sequence } The expression must be of type byte, short, int, or char Rupali Sherekar 2017

64 switch rules The data type of the values in the case statements must be compatible with the expression Each case value must be a unique The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, program control goes to the first line of code that follows the entire switch. Ex: seasons example, future example(shorten it for exam) Rupali Sherekar 2017

65 Nested switch You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. For example, the following fragment is perfectly valid: switch(count) { case 1: switch(target) { // nested switch case 0: System.out.println("target is zero"); break; case 1: // no conflicts with outer switch System.out.println("target is one"); } case 2: // ... Rupali Sherekar 2017

66 Home Work 1.Given a list of marks ranging from 0 to 100, Wap to print and compute the number of students having marks a)in the range 81 to 100 b)61 to 80 c) 41 to 60 d)0 to 40 2.Wap to print Write the difference between if and switch Rupali Sherekar 2017

67 Repetition/looping/iterative Statementswhile Do while for for each/enhanced for loop Nested loops Rupali Sherekar 2017

68 While while(condition) { // body of loop } Ex: int i=1;while(i<=10) { System.out.println(i); i++; // counter variable increased Rupali Sherekar 2017

69 Mind boggler(While loop)class NoBody { public static void main(String args[]) { int i, j; i = 100; j = 200; while(++i < j--) ; // no body in this loop System.out.println("Midpoint is " + i); } Rupali Sherekar 2017

70 Do-while do { // body of loop } while (condition); Ex: int i=1; do{System.out.println(i); i++ } This loop is executed atleast once even if the condition is false Rupali Sherekar 2017

71 Home Work Input a number and print its multiplication table (till 10) as follows: Ex : no=5 5x1=5 5x2=10 Make use of while loop Write a program to print the multiplication table of a number using command line arguments Rupali Sherekar 2017

72 Home Work Given an integer number, write a program using while loop to reverse the digits of the number. Also compute the sum of the digits of the number. Rupali Sherekar 2017

73 For loop for(initialization; condition; iteration) { // body }Ex:for(int n=10; n>0; n--) System.out.println("tick " + n); Ex: int a, b; for(a=1, b=4; a System.out.println("a = " + a); System.out.println("b = " + b); Rupali Sherekar 2017

74 // Parts of the for loop can be empty.class ForVar { public static void main(String args[]) { int i; boolean done = false; i = 0; for( ; !done; ) { System.out.println("i is " + i); if(i == 10) done = true; i++; } Rupali Sherekar 2017

75 For Each loop/enhanced for loopA foreach style loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. The general form of the for-each version of the for is shown here: for(type itr-var : collection) statement-block Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end With each iteration of the loop, the next element in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the collection have been obtained. Rupali Sherekar 2017

76 Enhanced for loop int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };int sum = 0; for(int x: nums) sum += x; Complete Example IMP:Its iteration variable is “read-only” as it relates to the underlying array. An assignment to the iteration variable has no effect on the underlying array. Rupali Sherekar 2017

77 Multi dimensional ArraysIn Java, multidimensional arrays are actually arrays of arrays 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. You can allocate the remaining dimensions separately. int twoD[][] = new int[4][]; twoD[0] = new int[5]; twoD[1] = new int[5]; twoD[2] = new int[5]; twoD[3] = new int[5]; Rupali Sherekar 2017

78 A different declarationint twoD[][] = new int[4][]; twoD[0] = new int[1]; // 0th row has 1 column twoD[1] = new int[2]; // 1st row has 2 columns twoD[2] = new int[3]; // 2nd row has 3 columns twoD[3] = new int[4]; // 3rd row has 4 columns Rupali Sherekar 2017

79 Initializing Multidimensional Arraysdouble m[][] = { { 0, 1,2, 3 }, { 5,6,11,10 }, { 7,12,13,8 }, { 4,22,15,9 } }; Rupali Sherekar 2017

80 Alternative Array Declaration Syntaxint al[] = new int[3]; int[] a2 = new int[3]; Rupali Sherekar 2017

81 Enhanced For loop and two dimensional ArraysFor Each3 Rupali Sherekar 2017

82 Jump Statements Java supports 3 jump statements break continue returnRupali Sherekar 2017

83 break Statement In Java, the break statement has three uses:-It terminates a statement sequence in a switch statement. It can be used to exit a loop. It can be used as like goto as below The general form of the labeled break statement is shown here: break label; The control of the program branches to the label block Rupali Sherekar 2017

84 continue statement Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for a particular iteration. When a continue statement is encountered in a loop, to the next iteration of the loop begins The statements in the loop after continue are not executed for that iteration Generally continue is used when some condition is satisfied Rupali Sherekar 2017

85 return The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. The return statement immediately terminates the method in which it is executed Rupali Sherekar 2017

86 Home work( for loop) WAP to print the following pattern 1 2 2 3 3 32 2 WAP to search a given value from an array. Rupali Sherekar 2017

87 Exam Questions Display * * * * * * *Program to find sum of digits of a number Use of break and continue Program that displays first 10 odd numbers and their factorials Print fibonacci numbers using recursion Logical unary , XOR , ternary operators Rupali Sherekar 2017

88 3. Find the smallest of 3 numbers using if statement 3 4 5 4 2. Write a program to find how many numbers are present between 11 and 20 which are divisiblw by 2 using do while loop 3. Find the smallest of 3 numbers using if statement Rupali Sherekar 2017

89 Exam Questions What is javadocThe javadoc command parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages that describe (by default) the public and protected classes, nested classes interfaces, constructors, methods, and fields. You can use the javadoc command to generate the API documentation or the implementation documentation for a set of source files. You can run the javadoc command on entire packages, individual source files, or both. Syntax: javadoc {packages|source-files} Rupali Sherekar 2017

90 Exam Questions What is javacThe javac tool reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files. Source code file names must have .java suffixes. For example, a class called MyClass would be written in a source file called MyClass.java and compiled into a bytecode class file called MyClass.class. By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with -d Rupali Sherekar 2017

91 javap javap [options] classfile... Options can be -version -publicPrints release information. -public Shows only public classes and members. -protected Shows only protected and public classes and members. -private OR -p Shows all classes and members. the javap command prints the package, protected and public fields, and methods of the classes passed to it. Rupali Sherekar 2017

92 Jdb- The java Debugger(EXAM QUESTIONS)The Java Debugger, jdb, is a simple command-line debugger for Java classes Syntax: jdb [ options ] [ class ] [ arguments ] The jdb command  provides inspection and debugging of a local or remote Java Virtual Machine (JVM). How to debugprogram nameis BOOLEAN jdb BOOLEAN(takes program in debug mode) stop at BOOLEAN:3(Set a breakpoint at some line say 3) run( starts the JVM)(runs the program and stops execution at breakpoint) step (execute next line of code) Continue step till the end You can add as many break points Rupali Sherekar 2017

93 Exam Questions javah The javah command generates C header and source files that are needed to implement native methods. The generated header and source files are used by C programs to reference an object's instance variables  Rupali Sherekar 2017

94 Difference between applications and appletsA program that runs on a stand alone computer Needs JVM Application has a single start point which is main method Can access any data or software available on the system Ex: public class MyClass { public static void main(String args[]) {} } Program that runs in a browser Needs JVM Applet application has 5 methods which will be automatically invoked on occurance of specific event cannot access any thing on the system except browser’s services Ex: import java.awt.*; import java.applet.*; public class Myclass extends Applet  { public void init() { } public void start() { } public void stop() {} public void destroy() {} public void paint(Graphics g) {} } Rupali Sherekar 2017

95 Basics: Package, Class and ObjectIt is important to understand the base terminology of Java in terms of packages, classes and objects. Rupali Sherekar 2017

96 Package Java groups classes into functional packages.Packages are typically used to group classes into logical units. For example, all graphical views of an application might be placed in the same package It is common practice to use the reverse domain name of the company as top level package. Rupali Sherekar 2017

97 Package Other main reason for the usage of packages is to avoid name collisions of classes. A name collision occurs if two programmers give the same fully qualified name to a class. The fully qualified name of a class in Java consists out of the package name followed by a dot (.) and the class name. Without packages, a programmer may create a Java class called Test. Another programmer may create a class with the same name. With the usage of packages you can tell the system which class to call. For example, if the first programmer puts the Test class into package report and the second programmer puts his class into package xmlreader you can distinguish between these classes by using the fully qualified name, e.g, xmlreader.Test or report.Test. Rupali Sherekar 2017

98 Class Def.: Template that describes the data and behavior associated with an instance of that class. The class can be seen as the blueprint of an object. It describes how an object is created. In Java source code a class is defined by the class keyword and class name must start with a capital letter. The body of a class is surrounded by {}. package test; class MyClass { } Rupali Sherekar 2017

99 Class The data associated with a class is stored in variables;the behavior associated to a class or object is implemented with methods. A class is contained in a Java source file with the same name as the class plus the .java extension. Rupali Sherekar 2017

100 Object Def.: An object is an instance of a class.The object is the real element which has data and can perform actions. Each object is created based on the class definition. Rupali Sherekar 2017

101 Inheritance A class can be derived from another class. In this case this class is called a subclass. Another common phrase is that a class extends another class. The class from which the subclass is derived is called a superclass. Inheritance allows a class to inherit the behavior and data definitions of another class. The following codes demonstrates how a class can extend another class. In Java a class can only extend a maximum of one class. package com.vogella.javaintro.base; class MyBaseClass public void hello() { System.out.println("Hello from MyBaseClass"); } } Rupali Sherekar 2017

102 package com.vogella.javaintro.base; class MyExtensionClass extends MyBaseClass { } Rupali Sherekar 2017

103 Object as superclass Every object in Java implicitly extends the Object class. The class defines the following methods for every Java object: equals(o1) allows checking if the current object is equal to o1 getClass() returns the class of the object hashCode() returns an identifier of the current object toString() gives a string representation of the current object Rupali Sherekar 2017

104 Java interfaces Interfaces are contracts for what a class can do but they say nothing about the way in which the class must do it. An interface is a type similar to a class. Like a class an interface defines methods. An interface can have only abstract methods, no concrete methods are allowed. Methods defined in interfaces are, by default, public and abstract – explicit declaration of these modifiers is optional. Interfaces can have constants which are always implicitly public, static and final. A class can implement an interface. In this case it must provide concrete implementations of the interface methods. If you override a method defined by an interface, you can also use Rupali Sherekar 2017