OOP

Page 1

1


2


Most popular platforms are Microsoft Windows, Linux, Solaris OS, and Mac OS.

3


Java Virtual Machine (JVM) is a set of computer software programs and data structures that use a virtual machine model for the execution of other computer programs and scripts. Functionality 1) Loading byte codes from the class files . 2) Verifying the loaded byte codes .

3) Linking the program with the necessary libraries . 4) Memory Management by Garbage Collection . 5) Managing calls between the program and the host environment. 6) Dynamic Exception Handling Refer: http://java.sun.com/docs/books/jvms/first_edition/html/Introduction.doc.html

4


List of Java API’s Refer: http://en.wikipedia.org/wiki/List_of_Java_APIs?_sm_au_=iVV5ts3FjtVRN4TQ

5


JRE and JDK Sun Microsystems provides two principal software products in the Java Platform, Standard Edition family: Java SE Runtime Environment (JRE) The JRE provides the libraries, Java virtual machine, and other components necessary for you to run applets and applications written in the Java programming language. This runtime environment can be redistributed with applications to make them freestanding. Java SE Development Kit (JDK) The JDK includes the JRE plus commandline development tools such as compilers and debuggers that are necessary or useful for developing applets and applications. JDK Tools & Utilities Documentation for the tools and utilities included in the JDK. Covers basic tools

6


The source code written in java will have .java extension. We need only Java Compiler and not JVM to compile java source code. The compiled code will have .class extension ( known as bytecode). This bytecode is loaded into the Java Runtime environment and executed within a Java Virtual Machine.

7


Java Virtual Machine The ClassLoader’s are responsible for loading classes from program and Java API. Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class.

The Java virtual machine organizes the memory it needs to execute a program into several runtime data areas. Each instance of the Java virtual machine has one method area and one heap. These areas are shared by all threads running inside the virtual machine. When the virtual machine loads a class file, it parses information about a type from the binary data contained in the class file. It places this type information into the method area. As the program runs, the virtual machine places all objects the program instantiates onto the heap. As each new thread comes into existence, it gets its own pc register (program counter) and Java stack. 8


9


package is a collection of all related classes, somewhat like a library.

Import statements must come after any package statements and before any code.

The import statement allows you to use a class directly instead of fully qualifying it with the full package name.

10


Commenting in Java: There are a number of reasons for including comments in source code. Some of the reasons for using comments are: Often comments are added at the start of each source file to give a description of what source the file contains and copyright information. The fields and methods of a class are often given brief comments that describe their purpose and what they do. Complex code is often commented heavily to make it clearer and easier to understand. The goal in commenting code is to make it possible for the reader to understand what the code does and how it achieves that. Commenting code is a fine balance, you should only provide comments where absolutely necessary and keep them brief. If code is too complex to understand you should consider revising the code to make it clearer or simpler, unless it is impossible to do so or you have very good reasons not to do so.

Note: Documentation comments describe Java classes, interfaces, constructors, methods, and fields, documentation comments should not be positioned inside a method or constructor definition block. 11


• A class definition contains all the variables and methods that make the program work. • This is contained in the class body indicated by the opening and closing braces. • The name of the public class declaration should be the same as the name of the file (case sensitive).

12


Compiling, Running and Debugging Java Programs 1. Before the Java virtual machine (VM) can run a Java program, the program's Java source code must be compiled into byte-code using the javac compiler. % javac -g Foo.java 2. Once you have successfully compiled your Java source code, you can invoke the Java VM to run your application's byte-code: % java <class with main method to run> [<command line args>, ...] 3. When the Java VM runs your program it searches for application .class files using the paths listed in your CLASSPATH environment variable. Reference http://www.cs.swarthmore.edu/~newhall/unixhelp/debuggingtips_Java.html

13


Refer - Help section of Eclipse. Click on Help -> Help Contents -> Java development user guide

14


Refer: http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html for java keywords. Refer: http://www.cafeaulait.org/course/week2/08.html for Identifiers in Java

15


Refer : Code Conventions for the Java Programming Language (http://www.oracle.com/technetwork/java/codeconv-138413.html)

16


Not valid list: 9pins // Begins with a digit testing1-2-3 // The hyphen is not an alphanumeric character MindTree_&_Associates // ampersand is not an alphanumeric character

17


Refer: https://konnect.mindtree.com/documentrepository/documentDetail.aspx?docID=268 0

18


Local variables scope is for the method call. They are created when an object is called and destroyed when method is popped out of stack. Instance variables are created for every object. They are destroyed when object is destroyed.

Static variables are loaded as soon as the class is loaded and shared by all the objects of class. They have the lifetime of JRE.

19


20


Variable Scope in a block

21


22


23


The main purpose of a use case diagram is to show what system functions are performed for which actor. Roles of the actors in the system can be depicted. http://goo.gl/lNiD2 Customer (actor) uses bank account to check balances of his/her bank accounts, deposit funds and withdraw cash.

24


Lesson 1 – Create Your First Java Class http://eclipsetutorial.sourceforge.net/totalbegginer01/lesson01.html Create Java project in Eclipse Create Java package Discuss the Lending Library Application Introduce classes and objects, naming conventions

Write a simple Java class (Person) Refer http://eclipsetutorial.sourceforge.net/Total_Beginner_Companion_Document.pdf and refer the videos.

25


All the methods declared deposit, withdraw and getBalance are instance methods. They can be called only by the objects of BankAccount.

26


An object stores its state (data) in instance fields . Field: a technical term for a storage location inside a block of memory.

27


28


Private members of a class cannot be accessed outside of a that class. Encapsulation = Hiding data and providing access through methods

29


Always the first argument to an instance method is implicit this. i.e. the reference to the object on which the method is called.

30


31


32


33


All instance variables will be initialized to their default values. i.e., integers to 0, double to 0.0, objects to null, boolean to false.

34


Constructor and method overloading, a type of polymorphism where different functions with the same name are invoked based on the data types of the parameters passed. Overloading Constructors: Option 1: you create object using default / parameter less constructor

ComputerTable table = new ComputerTable(); Option 2:you create object using parameterized constructor ComputerTable table = new ComputerTable(3,4,2.5);

35


The code snippet explains object creation using parameterized constructors.

36


Compiler creates default constructors only in scenario if we do not write any of our own parameterized constructors. Circle circle = new Circle(); // Compiler error: default constructor undefined

37


38


39


Objects created resides in the heap area. References to the object will be in Stack area. i.e., aRef and anotherRef are in stack but only one object of type SomeObject is created in heap area.

40


Only one BankAccount object is created. kavithaAccount and rahulAccount are one and the same. They are just to references to a single account.

41


1. == tests for identity (same reference), equals for identical content 2. Requirement: must override equals in BankAccount.

42


•Method overriding: •Method overriding is feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclass or parent classes. ( More details discussed later) •In equals() method do not include all the attributes.

•For an BankAccount accountNumber will be unique, hence comparing accountNumbers is sufficient •Similarly while comparing Employees “employeeId” will be sufficient. •But while comparing two rectangles we may have to consider both width and breadth.

43


44


45


46


Note: •Instance methods can access instance variables and instance methods directly. •Instance methods can access class variables and class methods directly. •Class methods can access class variables and class methods directly. •Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to

47


48


Static Methods can not use non-static fields and non-static methods. Reason: implicit variable “this� is not passed as argument to a static method. BankAccount acc = new BankAccount(2222.22); acc.getCount() ; method call will be converted to BankAccount.getCount( ) ; hence object reference (this) is not passed.

49


•Reference “accounts” contains the address to memory location in heap area. •The allocated memory contains on length variable which holds the size of array and slots to hold address of bank accounts. •By default each of these slots contain “null” ( Not referenced to any bank account )

50


addr1 --> address of first BankAccount addr2 --> address of second BankAccount

51


•The “accounts.length” variable is a read-only variable, which returns the size of array. •When value of i = 0, accounts[i].getBalance() returns 9999.22 •Similarly for the value of i = 1, accounts[i].getBalance() returns 56000.40

52


53


Refer - OOAD-Implementing Class Relationship in Java.pdf to know more on how to implement these class relationship in Java

54


55


Relationship between BankAccount and Customer is represented as aggregation.

56


Refer:http://www.objectmentor.com/resources/articles/umlClassDiagrams.pdf

57


BankAccount has a reference to its owner, the Customer object.

58


59


Student is-a Person.

60


In java every class is extended from java.lang.Object. Object is the supermost class. Some important methods present in java.lang.Object class: equals(), hashCode(), toString() , wait( ), notify(), notifyAll() and clone() Every class inherits these methods.

61


Answer: The statement is valid. 1) Every class extends Object. List of some methods inherited from Object : equals() , hashCode( ) ,toString( ) , wait( ) , notify(), notifyAll(). 2) The default implementation of equals() checks only object references and hence returns “false�.

You need to override the method and provide proper code for identity check.

62


63


The method setBalance() is protected. Can be accessed only by the owning class and sub classes of BankAccount. In CheckingAccount class, we override deposit() and withdraw() methods because we need to apply transaction fee.

64


Which overridden method to call is based on the actual object type and decided at runtime

65


In the above code example: set() is overloaded, String getName() is overriden.

66


•Upcasting is conversion up the inheritance hierarchy. •Downcasting is conversion down the inheritance hierarchy •Note that the “account” reference variable cannot access the members that are only available in CheckingAccount.

67


All the public and protected methods declared in BankAccount class can be accessed by an reference of BankAccount

68


Upcasting: BankAccount account = new SavingsAccount(); Actual object created is of type SavingsAccount, but referenced by BankAccount. BankAccount can send only messages it knows, not its sub types.

69


All the public and protected methods declared in BankAccount class plus the public and protected methods declared in SavingsAccount class can be accessed by an reference of SavingAccount

70


Answer: 1) Valid statement: It is upcasting. 2) Not Valid. It is a compiler error: Not all Person’s are students. You need to explicit cast while dowcasting 3) Compiles but run time you get ClassCastException. 4) Valid: same as Answer 1.

71


How to call parameterized constructor of base (super) class.

72


Answers: 1) Compiler Error: Object created is of “B” type but the reference type is “A”. “A” type refernece can invoke only methods first(), second() and all the methods inherited from java.lang.Object class. 2) Valid Statement:

nobj.second() -- > “Second method”. Inherited method

nobj.second(22) ---> “Second method with data”. It’s own method.

73


74


75


76


Compiler error. B is-a A. But not all A’s are of type B.

77


obj.test() ---> dynamic binding obj.best( ) - - -> Not valid ( Compiler error). Reference type A cannot send message best().

78


Only instance methods are virtual in java. Static methods are not virtual and hence static binding takes place. obj.test() ---> static binding . The call is converted into A.test().

79


80


Interface methods are implicitly abstract and public. If a class does not realize the behavior specified in an interface, then the class becomes incomplete and hence should be marked abstract.

81


We need to greet all the guests invited for a function. Human and Computer can take turns to greet them. Electricity/Computer problem --- Human takes over. Electricity/Computer problem solved --- Computer takes over ( Human takes rest).

82


Flyable and Comparable are interfaces. Eagle is a Bird and capable of Flying, Eagle implements fly(). AirVehicle is a Vehicle and capable of Flying and implements fly(). That does not put Eagle and AirVehicle into a single family (No inheritance). A class can implement multiple interfaces. All AirVehicle’s are comparable and Flyable. AeroPlane extends AirVehicle and hence it also realizes both the capabilities Flyable and Comparable.

83


Answer: 1) Invalid: Cannot instantiate an interface 2) Valid: AirVehicle implements Comparable and hence any classes extended from AirVehicle are Comparable 3) Invalid: Flyable interface can be used to invoke only methods declared in Flyable interface. AirVehicle class contains compare() method but it is not realized from Flyable interface.

84


All are valid. All the classes used implement Comparable interfaces. Note: Human should not be compared with Car or Bird and vice versa. Need to take care of this in logic.

85


Refer : http://www.oodesign.com/open-close-principle.html for Open-Close Principle

86


Factories can be used to decouple two layers. It helps in changing different strategies without effecting the client code.

87


88


89


90


91


Refer: https://konnect.mindtree.com/documentrepository/documentDetail.aspx?docID=103 6

92


93


94


95


96


97


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.