• No results found

Core_java

N/A
N/A
Protected

Academic year: 2021

Share "Core_java"

Copied!
106
0
0

Loading.... (view fulltext now)

Full text

(1)

What is Java?

Java is a internet software developed by Sun Microsystems for development of distributed applications.

What is software?

Is a set of programs meant for performing some specific operation in real world we have 3 types of software they are.

Types of java application

Standalone ApplicationWeb ApplicationEnterprise ApplicationMobile Application Features and Buzzwords of Java

Sun Microsystems has provided 13 features for java language 1. Simple

2. Platform Independent 3. Architectural neutral 4. Portable

5. Multithread

6. Networked Programming Language 7. Distributed Programming Language 8. High Performance 9. High Interpreted 10. Secured 11. Robust(Strong) 12. Dynamic 13. OOPL...

Features of a language are nothing but the services or facilities provided by language vendor to the industry programmer.

(2)

1) Simple:

2) Java is simple programming language because of the following factors.

a) Java programming language eliminates a complex concept called pointers hence we are able to develop the application with less time and it will take less execution time because of magic of Byte code.

3) Let us consider the following Diagram 4)

5) Byte Code: Byte code is set of optimized instructions generated during compilation phase by the java compiler and nature of byte code is so powerful than ordinary pointer code.

6) JVM: JVM is set of programs developed by sun Microsystems and supplied as a part of JDK and its role is reading line by line of byte code and converting into native understanding form of OS.

7) Note: Byte code is OS independent and JVM is OS dependent.

8) JIT (Just in time compiler): JIT is a program developed by sun Microsystems added as a part of JVM to speed up the interpretation phase by reading the entire section of byte code.“Java is one of the compiler and interpretation based prog lang”

9)

10) b) Java programming environment contains inbuilt garbage collector program.

11) Garbage Collector: Is a system background java program which is running along with our regular java program for collecting un-used/un-reference memory space and it improves the performance if java application.

12) Garbage program is internally running for regular intervals of time. 13)

14) Platform Independent: The language/technology related application are said to platform independent if and only if those application run on every OS without considering their providers / vendors.

15) In order to say a language / technology are platform independent, it has to satisfy the following properties.

16)

a) The data types of the language must take the same amount of memory space on all OS. b) The language / technology must contains some special powerful internal programs which

will convert the native understanding form of one OS to the native understanding form of another OS.

17) Architecture Neutral: Java’s byte code is not machine dependent. It can run on any machine with any processor and any operating system.

18) Portable: Java does not have implemented-dependent aspects. So the results will be same on all machine, portable means yielding same results on different machines.

(3)

19) Multithreading: The basic aim of multithreading is to achieve the concurrent execution. A flow of control in java is known as thread.

 The purpose of thread concept is to execute user define method which contains the logic of the java program.

 If any java program contains multiple flow of controls then that java program is known as multithreaded.

 The language like C, C++, Pascal, COBOL etc come under single threaded modelling language because their execution environment contains single flow of control.

 In general single threaded modelling language provides sequential execution but not concurrent execution and they not contain any library for development of multithreaded application.

 The language like Java and .Net are threaded as multithreaded because their execution environment provides and contains multiple flow of controls.

 In Java programming we have the following API for development of multithreading application

 Java.lang.Thread(class).  Java.lang.Runnable(Interface).

20) Whenever we write a java program 2 types of threads exist 1) Fore-ground / child thread.

2) Back-ground / parent thread.

21) “Multitasking concept of java is one of the specialized form of multitasking concept of OS.

22) Networked: To share the data between multiple machines which are located either in same network or in different network, Intranet application will be developed by J2SE with network programming concept.

23) Distributed: According to real world project, java project are classified into 2 types i. Centralized Application.

ii. Distributed Application.

i) Centralized application: Centralized application are those which runs in the context of single server and their result can be accessible across the globe and they are operated by authorized people only. (Banking , insurance ...)

ii) Distributed application: which runs in the context of multiple servers and result are accessible across the globe and they are operated by both authorized and unauthorized user.

24) Note: Centralized application will have private URL. 25) Distributed application will have public URL.

26) High Performance: Java is one of the high performance programming language because of the following factors

i. Automatic memory management due to inbuilt garbage collector. ii. Java is free from pointers.

iii. Due to JIT which enhances the speed of the execution.

27) Robust: The language like Java and .Net are threaded as Robust/Strong programming language because Runtime error are effectively addresses by the concept called Exception Handling. OR java programs will not crash because of its exception handling and its memory management features.

(4)

28) Highly Interpreted: In the older version of java (JDK 1.0) compilation phase was very faster and interpretation phase was very slow this is one the industry programmer complimented and compliant to sun Microsystems.

29) Sun Microsystems has taken this task as challenging issue and they developed a program called JIT and added as part of JVM to speed up the interpretation phase by reading entire section of byte code at once.

30) Secure: Security is one of the principal in IT world for preventing / protecting the unauthorized modification on confidential data. The language like Java and .Net are treated has high secured programming language because their API contains readily available security programs in a package called javaX.security.*;

31) Dynamic: In any programming language, if we write a program and that program accepts input then the input of program is stored in the main memory by allocating sufficient amount of memory space.

32) In any programming language memory allocation can be done in 2 ways i. Static Memory Allocation.

ii. Dynamic Memory Allocation. 33)

i) Static Memory Allocation is one in which memory will be allocated for the impact of the program at compile time because of static Memory allocation we get the following drawbacks

a. Waste of memory space. b. Loss of Data.

c. Overlapping of Existing Data.

ii) Dynamic Memory Allocation is one in which memory will be allocated for the input of the program at run time .

o Java follows only dynamic memory allocation but not static memory allocation.

o To allocate the memory space dynamically is java programming we use operator called new.

34)

(5)

36) What is the architecture of JVM? 37)

38) JVM has various sub components internally. You can see all of them from the above diagram.

1. Class loader sub system: JVM's class loader sub system performs 3 tasks a. It loads .class file into memory.

b. It verifies byte code instructions.

c. It allots memory required for the program.

2. Run time data area: This is the memory resource used by JVM and it is divided into 5 parts a. Method area: Method area stores class code and method code.

b. Heap: Objects are created on heap.

c. Java stacks: Java stacks are the places where the Java methods are executed. A Java stack contains frames. On each frame, a separate method is executed.

d. Program counter registers: The program counter registers store memory address of the instruction to be executed by the micro processor.

e. Native method stacks: The native method stacks are places where native methods (for

example, C language programs) are executed. Native method is a function, which is written in another language other than Java.

3. Native method interface: Native method interface is a program that connects native methods libraries (C header files) with JVM for executing native methods.

(6)

4. Native method library: holds the native libraries information.

5. Execution engine: Execution engine contains interpreter and JIT compiler, which covert byte code into machine code. JVM uses optimization technique to decide which part to be interpreted and which part to be used with JIT compiler. The Hotspot represents the block of code executed by JIT compiler.

39) Java memory management

40) Java Heap Memory v/s Stack Memory 41) Java Heap Memory

42) This is the memory where the Objects and JRE classes are stored at the runtime. When the object is created it is stored in the heap. Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application. In multithreading the objects are available for all the threads, means all the threads share the same heap

43) Java Stack Memory

44) Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory.

45)

46)

publicclassMemory {

47)

48)

publicstaticvoidmain(String[] args) { // Line 1

49)

inti=1; // Line 2

50)

Object obj = newObject(); // Line 3

51)

Memory mem = newMemory(); // Line 4

52)

mem.foo(obj); // Line 5

53)

} // Line 9

54)

55)

privatevoidfoo(Object param) { // Line 6

56)

String str = param.toString(); // Line 7

57)

System.out.println(str);

58)

} // Line 8

59)

60)}

(7)

61)

 When we run a program it loads all the runtime class into the heap space

The main method is found at the Line-1 now the memory for the main method is allocated in the stack region by the main thread.

We are creating the local variables at Line-2 it is going to be created in the stack region of main block.

In Line-3 we are creating the object the object is going to be created in the heap region and its reference is stored in the stack region, similarly in Line-4 we are creating one more object. In Line-5 we are calling the method foo( ) than the memory for the method is going to be

allocated in the stack region ( the block of memory is going to be allocated in the stack region). Since java is pass by value the one more reference is created at the Line-6

 From the foo( ) method we are creating one more String object it is going to be created in the heap region, the reference is present in the stack region inside the stack. ( String objects are going to be created in the String pool in the heap)

Has soon has the control reach Line-8 the method looses the scope, than the memory that was allocated to the method foo( ) becomes free

When the Line-9 is executed than the main method also going to loose the scope, and the memory allocated to it also get free. Than java runtime will free al the memory allocated and the execution completes.

62)

63) Difference between Heap v/s Stack

 Objects stored in the heap are globally accessible whereas stack memory is not accessed by other threads .

 Heap is the place where objects are stored, the stack region is the place where the local variables are stored and the reference to the objects that are stored in heap region.  Stack memory is short lived where has heap memory is going to exists till the end of

application execution.

 When stack memory is full it throws java.lang.StackOverFlowError , where has if heap memory is full java.lang.OutOfMemoryError

 Stack memory is very less when compared to Heap  Stack is very fast when we compared to Heap 64) How to set a path of JDK?

(8)

66) How to change the driver?

 Step1 C:\User\Vikas> cd..  Step2 C:\>d:

 Step3 D:\> 67) How to create a folder?

 Step1 D:\> mkdir NewFolderName

 Step2 D:\NewFolderName>mkdir OtherFolder  Step3 D:\NewFolderName\OtherFolder> 68) How to create a java file?

 Step1 D:\NewFolderName\OtherFolder> notepad FileName.java

69) (if the notepad does not open than open notepad and save it inside a folder (OtherFolder) and save with .java extension

70) How to compile a java program?

 Step1 D:\NewFolderName\OtherFolder>javac FileName.java  Step2 D:\NewFolderName\OtherFolder>java FileName 71)

72)

73) Data type

74) A data type is a classification of the type of data that a variable can hold in computer programming.

75) Data types in Java are classified into two types:

1. Primitive—which include integer, character, boolean, and floating Point type values. 2. Non-primitive—which include Classes, Interfaces, Object type and Arrays.

76)

77) Primitive Data Types: 78)

79) There are eight primitive data types supported by Java. 80)

81) byte:

 data type is an 8-bit

 value from -128 to 127 (27 to 27-1)  default value is 0

82) short:

 data type is an 16-bit

 value from -32,768 to 32,767 (215 to 215-1)  default value is 0

83) int:

 data type is an 32-bit

 value from - 2,147,483,648 to 2,147,483,647 (231 to 231-1)  default value is 0

84) long:

 data type is an 64-bit  value from (263 to 263-1)  default value is 0L 85) float:

(9)

 data type is an 32-bit

 Float is mainly used to save memory in large arrays of floating point numbers  default value is 0.0f

86) double:

 data type is an 64-bit

 This data type is generally used as the default data type for decimal values, generally the default choice

 default value is 0.0 87) boolean:

 it represents one bit of information

 it can contain only true or false ( no 1 or 0 is allowed )  default value is false

88) 89) char:

 its sixe is 16 bit

 it is used to store only one character

 default value is space ( we represent it by 0) 90)

91) Variables

92) A variable is the one which holds some value which can be altered later in the program. Or it is the named storage which can be altered later in the program.

93) int i; //declaration 94) i = 20; // initialisation

95)

Methods

 Methods are the one which contains group of statements, which are used to perform some functionality. Which are called by using their names.

 Methods contains group of statements

 A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name

 It increase the readability and reusability of code

 In java we call functions has methods, because hear the methods can be written only inside class but not outside the class has in C++

 Methods are used to tell the behaviour of the object Syntax

96) <return type> <method Name>(arguments)

97) {

98) // Body of method

99) //return keyword with returning

value 100) } 101) Example 102) int add() 103) { 104) return 5+6; 105) } 106)

(10)

107) In the above example the add() method returns 11, which of type int 108) 109) void drink() 110) { 111) System.out.println("Drinking water...!"); 112) } 113)

114) In the above example the drink() method will not return anything so the return type is void.

115) Note:

 If we specify any return type while declaring than that method should return that type value.

 The return statement word should be present at the last. In the séance the return statement should be logically the last line in the method block

 If the return type is void means we need not to specify the return statement at the last. Compiler itself is going to write the return statement. If at all if you need to specify means do has below.(a empty return statement)

 void drink()

116) {

117) System.out.println("Drinking water...!");

118) return;

119) }

 the method can have empty return statement, if the return type of the method is void. But that return statement should not even return 0(zero) , ‘ ’(space) or null

 Advantage is code reusability  There are two types of methods

Static methodsNon-Static methods

Static methods : These methods a declared using the static key word o Example

120) void static method1()

121) {

122) System.out.println("In method1() its a static method...!");

123) }

 Static method can be accessed directly by just using the class name. From static methods we cant accesses non static members directly

o Example : 124) class AddingMethod

125) {

126) static void add(int i , int j)

127) {

128) System.out.println("Addition of two numbers...");

129) int sum=0;

130) sum = i + j;

131) System.out.println("Sum of "+i+" and "+j+" is = "+sum);

132) }

133) void sub(int m , int n)

(11)

135) System.out.println("Addition of two numbers..."); 136) int diff = 0; 137) diff = m - n; 138) System.out.println("Difference of "+n+" from "+m+" is = "+diff); 139) } 140) } 141) class MethodMember 142) {

143) public static void main(String args[])

144) {

145) AddingMethod.add(50,60); // static method is called by

class name

146) AddingMethod.sub(150,60); //Error sub is non-static

147) }

148) }

Non-static methods : These methods are declared without static keyword. Non-static methods can accesses static members directly

o Example 149) void method2()

150) {

151) System.out.println("In method1() its a non-static method...!");

152) }

Non-static members are called by creating the instance of the class or by using the object reference of the class

153) 154) o Example 155) 156) class MethodMember 157) {

158) public static void main(String args[])

159) {

160) AddingMethod.add(50,60); // static method is called by class

name AddingMethod ref1 = new AddingMethod();

161) ref1.sub(150,110); // non-static method can be called only using reference 162) AddingMethod ref2 = new AddingMethod();

163) ref2.add(80,20); // static method can be also called by using reference

164) }

165) }

166) class AddingMethod

167) {

168) static void add(int i,int j)

169) {

170) System.out.println("Addition of two numbers...");

171) int sum=0;

172) sum = i + j;

173) System.out.println("Sum of "+i+" and "+j+" is = "+sum);

(12)

175) void sub(int m , int n)

176) {

177) System.out.println("Addition of two numbers...");

178) int diff = 0; 179) diff = m - n; 180) System.out.println("Difference of "+n+" from "+m+" is = "+diff); 181) } 182) }

183) Static members 184) Non-Static members

185) static members are also known has Class members

186) non-static members are also known has Object members

187) static members are loaded only once for entire program execution

188) non-static members are loaded for every instance of class

189) If static members are changed it gets changed for entire program

190) if a non-static members of an instance is changed that change will not reflect in other instance of class

191) static members can be used across any objects

192) non-static members cannot be shared across the Object

193) static members are loaded into heap by class loader

194) non-static members are loaded into heap when JVM encounter Object creation statement 195) all static members reside in common area

known has static pool

196) non-static member are loaded into Object memory after object creation

197) static members are accessed through class name

198) non-static members are accessed by using the reference variable

199) 200)

(13)

201) Class

202) A class is the blueprint from which individual objects are created. Class is a one which contains states (variables) and behaviour (methods)

203) 204) Syntax – 205) class <className> 206) { 207) //code 208) } 209)

210) public class Lover

211) {

212) String name; //state

213) int age; //state

214) char sex; //state it takes only M or F

215) double height; //state

216)

217) void takeToPark() //behaviour

218) {

219) System.out.println("Take in a R-15");

220) }

221)

222) int spendMoney() //behaviour

223) { 224) int money=5000; 225) return money; 226) } 227) } 228) 229) Object

230) An object is an instance of a class. The term ‘object’, however, refers to an actual instance of a class. Every object must belong to a class.

231) Note  Objects have a lifespan but classes do not

232) Object of a calss can be created using the new keyword and name of the class.

233) new <className>;

234) public class Test 235) {

236) public static void main(String[] args) 237) {

238) Lover l1 = new Lover();

239) Lover l2 = new Lover();

240) }

241) } 242)

(14)
(15)

245)

OOPS CONCEPTS

246)

Inheritance

247) It is one of the oops concept of java. Inheritance means, it’s a mechanism where the child class acquires the properties of the parent class or supper class.

248) Example : 249) class Boy 250) { 251) String name; 252) int age; 253) 254) void factory() 255) {

256) System.out.println("factory() method of boy");

257) }

258)

259) void banglo()

260) {

261) System.out.println("banglo() method of boy");

262) }

263) } 264)

265) class Girl extends Boy 266) { 267) double height; 268) String colour; 269) 270) void job() 271) {

272) System.out.println("job() method of Girl");

273) }

274)

275) void prepareFood()

276) {

277) System.out.println("prepareFood() method of Girl");

278) }

279)

280) void details()

281) {

282) System.out.println("Name "+name+" age is "+age+" height is "+height+" and colour is "+colour);

283) }

284) } 285)

286) class InheritanceProgram 287) {

(16)

288) public static void main(String args[])

289) {

290) Girl ref = new Girl();

291) ref.name="reka"; 292) ref.age=20; 293) ref.factory(); 294) ref.banglo(); 295) 296) ref. height =5.5; 297) ref.colour="pink"; 298) 299) ref.job(); 300) ref.prepareFood(); 301) ref. details(); 302) } 303) } 304) OutPut 305) 306) C:\Users\Vikas\Desktop\java>javac InheritanceProgram.java 307) 308) C:\Users\Vikas\Desktop\java>java InheritanceProgram 309)

310) factory() method of boy 311) banglo() method of boy 312) job() method of Girl

313) prepareFood() method of Girl

314) Name reka age is 20 height is 5.5 and colour is pink 315)

316) In the above example we see the single level inheritance, hear the Girl class inherit all the properties of Boy class . The name, age , factory(), bangle() of Boy class is acquired by the Girl class, so by creating the object of Girl class I can accesses both the Boy class and Girl class properties.

317)

318)

319)

java supports inheritance there are many types of in heritance o single inheritance ( above example )

(17)

o hierarchical inheritance 320)

321) Example for multilevel inheritance

322) class Parent 323) {

324) }

325) class Boy extends Parent 326) {

327) }

328) class Girl extends Boy 329) {

330) }

331) In the above example the Boy class can acquire the properties of Parent class, mean while has Girl class extends Boy class, so a Girl class can acquire the properties of both the Parent class and the Boy class.

332)

333) 334) 335) 336)

(18)

337) Example for hierarchical inheritance 338)

339) Note : Java does not support the multiple inheritance where has it only

supports multilevel inheritance. 340)

341) If class A and class B have same methods than the class C will be in confusion to take the method from which class so this concept was ruled out in java.

342) If you create the Object of class C than the constructor is called, hear that

constructor will execute the super statement, here again there is a confusion which is parent class and whose constructor is need to be called

(19)

343) IS-A Relationship

 This refers to inheritance or implementation.  Expressed using keyword “extends”.

 Main advantage is code reusability. 344) 345) 346) class Animal 347) { 348) void walk() 349) { 350) System.out.println("Walk"); 351) } 352) void eat() 353) { 354) System.out.println("eat food"); 355) } 356) } 357)

358) class Cow extends Animal //Cow is-a Animal

359) {

360) void giveMilk()

361) {

362) System.out.println("cow give milk");

363) } 364) void sound() 365) { 366) System.out.println("ambaa...ambaaa"); 367) } 368)} 369)

370) class Dog extends Animal //Dog is-a Animal

371) { 372) void sound() 373) { 374) System.out.println("bow...bow"); 375) } 376) }

377) public class Test {

378) public static void main(String[] args) {

379) Animal a = new Cow();

380) a.walk();

381) a.eat();

382)

383) a.giveMilk(); //not possible Parent reference cant accesses child member 384)

385) a.sound(); //not possible Parent reference cant accesses child member 386)

387) Dog d = new Animal(); //not possible because child reference cannot be give to Parent object

388)

389) Cow c = new Cow();

390) c.walk();

391) c.eat();

392) c.sound();

(20)

394) }

395) }

396)

Whatever the parent class has, is by default available to the child. Hence by using child

reference, we can call both parent and child class methods.

Whatever the child class has, by default is not available to parent, hence on the parent class reference we can only call parent class methods but not child specific methods.

Parent class reference can be used to hold child class objects , but by using that reference we can call only parent class methods but not child specific methods.

We cant use child class reference to hold parent class objects 397) HAS-A Relationship

 Has-A means an instance of one class “has a” reference to an instance of another class or another instance of same class.

 It is also known as “composition” or “aggregation”.

 There is no specific keyword to implement HAS-A relationship but mostly we are depended upon “new” keyword.

398) 399) class Mobile 400) { 401) void giveCall() 402) { 403) //some code 404) } 405) void playGame() 406) { 407) //some code 408) } 409) } 410) class Person 411) {

412) Mobile m = new Mobile(); //So we can tell person has a Mobile

413) void eatFood() 414) { 415) //some code 416) } 417) void drinkWater() 418) { 419) //some code 420) } 421) }

422) public class Test

423) {

424) public static void main(String[] args) 425) {

426) Person p = new Person();

427)

428) p.m.giveCall(); //Person has a mobile so accessing it using person object

429) p.m.playGame(); //Person has a mobile so accessing it using person object

(21)

430) }

(22)

432) Variables 433)

434)

435) Local Variables

436) Any variables declared inside a method or constructor is called has local variables. Local variables need to be initialised before they are used. Local variables do not have default value.

437)

438) Global Variables

439) Any variables declared inside the class but outside the methods or constructors are called has global variables. Global variables will take a default if u have not initialised it.

440) Instance variables the global variables declared without static keyword is called has instance variables. These variables get initialised whenever the object is created.

441) Instance variables are one for the object.

442) Static variables the global variables declared with the static keyword are called has static variables. These variables will get initialized whenever the class loads into memory. These variables are one for the class.

443)

444) An argument is an expression passed to a function or constructor, where a parameter is a reference declared in a function declaration or even constructor.

445) class Gift { 446)

447) void buy(String name , int cost) //name and cost r called has formal parameters

448) {

449) //some code hear

450) }

(23)

452) { 453) //some code 454) } 455) 456) 457)

458) public static void main(String[] args)

459) {

460) double e = 5.5;

461) char v = ‘M’;

462) Gift g = new Gift(e , v); //e and v are the actual arguments 463)

464) String hesaru = "barby";

465) int money = 200;

466)

467) g.buy(hesaru , money); //hesaru and money are the actual arguments 468) }

469) }

470) 471)

472) Constructor

Constructor is special kind of method which gets called when object is createdConstructor don’t have return type

Constructor cannot be inherited

Constructor name is same has the class name

Every class should have a constructor, if we don’t write a constructor compiler will write a default constructor.

Compiler will not write a default constructor, if we are going to write any of the constructor explicitly

Constructor with no parameters or a zero parameter constructor is called has default constructor

Constructor with parameter is called has parameterized constructor. These constructor is used to initialise the instance variables at the time of creating objectSyntax 473) <accesses-specifier> ClassName ( ) 474) { 475) //some code… 476) } 477) 478) Eg :- class Cow 479) {

480) //zero parameter constructor of Cow Class

481) public Cow()

482) {

483) System.out.println("I am in Cow class constructor...!");

484) }

(24)

486) Note : If you don’t write any constructor inside a class by default there will be a default constructor inside that class, and that default constructor will be similar like a zero-parameterized constructor. Zero zero-parameterized constructor is also called has default constructor.

487) 488)

(25)

489) class Cow 490) {

491) //zero parameter constructor of Cow Class

492) public Cow()

493) {

494) System.out.println("I am in Cow class constructor...!");

495) }

496) }

497) class Test1 498) {

499) public static void main(String[] args)

500) {

501) System.out.println("Before creating object");

502) Cow ref = new Cow(); //when this line is executed the Cow() constructor is called 503) System.out.println("After creating 1st object");

504) new Cow(); // when this line is executed again the Cow() constructor is called

505) System.out.println("After creating 2nd object"); 506) }

507) } 508) Output :

509) Before creating object

510) I am in Cow class constructor...! 511) After creating 1st object

512) I am in Cow class constructor...! 513) After creating 2nd object

514) 515)

(26)

516) Constructor Over Loading

517) A class can contain more than one constructor inside it, but they should vary with number of parameters or type of parameters. This concept is called has contractor overloading.

518) class Cow 519) {

520) public Cow()

521) {

522) System.out.println("I am in Cow() constructor...!");

523) }

524)

525) public Cow(int leg)

526) {

527) System.out.println("I am in Cow(int leg) constructor...!");

528) }

529)

530) public Cow(double height)

531) {

532) System.out.println("I am in Cow(double hight) constructor...!");

533) }

534)

535) public Cow(int ears , int mouth)

536) {

537) System.out.println("I am in Cow(int ears , int mouth) constructor...!");

538) }

539) } 540)

541) These constructors can be called by creating a object like 542)

543) new Cow(); // Cow() constructor is called

544) new Cow(4.5); // Cow(double height) constructor is called

545) new Cow(2,1); // Cow(int ears , int mouth)constructor is called 546) new Cow(4); // Cow(int leg) constructor is called

547) Note :

 The parameterized constructor is used to initialize the instance variables of the class  If you don't define a constructor, the default constructor (which has no parameters)

will be generated by default.

 If you have any user-defined constructor, the default constructor will not be generated at all.

548)

549) this key word

(27)

if there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity

this keyword refers to current class instance variables 550)

551) Example :

552) class SweetHeart

553) {

554) String name;

555) int age , salry;

556) double hight;

557)

558) SweetHeart(String name , double hight , int age , int salry)

559) { 560) this.name=name; 561) this.hight=hight; 562) this.age=age; 563) this.salry=salry; 564) } 565) void detailsOfAge() 566) {

567) System.out.println("My sweetHeart name is "+name+" and the age is "+age);

568) }

569) void fullDetails()

570) {

571) System.out.println("My sweetHeart name is "+name+" and the age is "+age+" hight is "+hight+" and get a salry rs "+salry);

572) }

573) }

574)

575) class Test2

576) {

577) public static void main(String[] args)

578) {

579) SweetHeart ref1=new SweetHeart("Geetha",4.9,20,15000);

580) ref1.fullDetails();

581)

582) SweetHeart ref2=new SweetHeart("Ramesh",5.5,18,20000);

583) ref2.fullDetails();

584)

585) //To print only name and age call detailsOfAge() 586)

587) ref1.detailsOfAge();

588) ref2.detailsOfAge();

589)

590) }

591) } Try this program and write the output. Pleas practice more programs on all topics 592)

(28)
(29)

594) Note : 595) class SweetHeart 596) { 597) String name; 598) int age,salry; 599) double hight; 600)

601) SweetHeart(String name , double hight , int age , int salry)

602) { 603) name=name; 604) hight=hight; 605) age=age; 606) salry=salry; 607) } 608) }

609) Hear the local variables get more priority so the instance variables will not get a scope to get initialize,

610) name (local variable) is different than the name (instance variable). So we make use of this keyword to initialize the instance variables of the class, when both local and instance variables name is same. 611)  class Test 612) { 613) Test() 614) { 615) return ; 616) } 617) }

618) This example will compile and run. But return keyword should not return any value

619)

620) Constructor chaining

In Java you can call one constructor from another and it’s known as constructor chaining in Java.

We can call the same class constructor using this key wordthis( ) must be the 1st line inside a constructor

621) Example :

622) class Bus

623) {

624) Bus()

625) {

626) this("Banglore"); //this(“Banglore”) will call Bus(String name)

627) System.out.println("Bus is empty...!");

628) }

(30)

630) Bus(String name)

631) {

632) this(10); //this(10) will call Bus(int num) 633) System.out.println("Bus is having a name...!");

634) }

635)

636) Bus(int num)

637) {

638) System.out.println("Bus is having a NUMBER...!");

639) }

640) }

641) class ConstructorChaining 642) {

643) public static void main(String[] args)

644) {

645) new Bus();

646) }

647) }

Output :

648) Bus is having a NUMBER...! 649) Bus is having a name...! 650) Bus is empty...!

We can call the parent (super) class constructor by using super key word

651) super( ) is used to call the immediate parent class constructor. super( ) must be the 1st

line in constructor Example :

652) class Train

653) {

654) Train()

655) {

656) this("Hassan"); //this(“Hassan”) will call Train(String name)

657) System.out.println("Train is empty...!");

658) }

659) Train(String name)

660) {

661) this(55); //this(10) will call Train(int num)

662) System.out.println("Train is having a name...!");

663) } 664) Train(int num) 665) { 666) System.out.println("Train is having a NUMBER...!"); 667) } 668) }

669) class Bus extends Train 670) {

671) Bus()

(31)

673) this("Banavara"); //this(“Banglore”) will call Bus(String name) 674) System.out.println("Bus is empty...!"); 675) } 676) Bus(String name) 677) {

678) this(10); //this(10) will call Bus(int num)

679) System.out.println("Bus is having a name...!");

680) }

681) Bus(int num)

682) {

683) super();//super() will call Train() because Train is parent class

684) System.out.println("Bus is having a NUMBER...!");

685) }

686) }

687) class ConstructorChaining 688) {

689) public static void main(String[] args)

690) {

691) new Bus();

692) }

693) }

694) OutPut :

695) Train is having a NUMBER...! 696) Train is having a name...!

697) Train is empty...!

698) Bus is having a NUMBER...! 699) Bus is having a name...! 700) Bus is empty...!

701)

702) Note :

703) Constructor chaing should not lead to recursion.

704) Example:

705) class Bus extends Train 706) { 707) Bus() 708) { 709) this("Banavara"); 710) System.out.println("Bus is empty...!"); 711) } 712) Bus(String name) 713) {

(32)

714) this(10);

715) System.out.println("Bus is having a name...!");

716) }

717) Bus(int num)

718) {

719) this(); // Hear the error occurs because it is leading for

recursion

720) System.out.println("Bus is having a NUMBER...!");

721) }

722) }

723) super( ) and this( ) cannot be present inside the same constructor. Any one can be present inside.

724) Bus(int num)

725) {

726) this();

727) super(); //Error because super( ) must be 1st line 728) System.out.println("Bus is having a NUMBER...!");

729) } 730) Bus(int num)

731) {

732) super();

733) this(); //Error because this( ) must be 1st line 734) System.out.println("Bus is having a NUMBER...!");

735) }

(33)

737) Instance-Init Block (non-static block)

Instance block will execute whenever a new object is created.

If there are more than one instance block than it will execute in the sequence of the order they are written

These are used to declare the instance variables of the class 738) class Run1

739) {

740) //instance block

741) {

742) System.out.println("In INIT block of Run1");

743) } 744) } 745) class Run2 746) { 747) //instance block 748) {

749) System.out.println("In INIT block of Run2");

750) }

751) }

752) class Test1

753) {

754) public static void main(String[] args)

755) {

756) new Run1();//Now the instance blcok of Run1 class will execute 757) System.out.println("1st instance block is created...!");

758) new Run2();//Now the instance blcok of Run2 class will execute

759) } 760) } 761) 762) OutPut 763) D:\bin>javac Test1.java 764) D:\bin>java Test1 765) In INIT block of Run1

766) 1st instance block is created...! 767) In INIT block of Run2

768) Static Block

It's a block of code which is executed when the class gets loaded by a class loader. It is meant to do initialization of static members of the class.

static block executes once in life cycle of any program another property of static block is that it executes before main method

Static blocks are also called Static initialization blocks 769)

770)

771) class Test1 772) {

(34)

774) {

775) System.out.println("In Test1 static block");

776) }

777) } 778)

779) class Demo1 780) {

781) public static void main(String[] args)

782) { 783) new Test1(); 784) } 785) } 786) 787) OutPut 788) D:\bin>javac Demo1.java 789) D:\bin>java Demo1 790) In Test1 static block 791)

792) class Test1 793) {

794) static

795) {

796) System.out.println("In Test1 first static block");

797) }

798) static

799) {

800) System.out.println("In Test1 second static block");

801) }

802) public static void main(String[] args)

803) {

804) new Test1(); } }

805) OutPut

806) D:\bin>javac Demo1.java 807) D:\bin>java Demo1 808) In Test1 first static block 809) In Test1 second static block 810)

811) Note – If there are multiple static blocks than it will execute in the sequence has they present

(35)

813)

814) Static Block 815) Non-Static Block

816) Gets executed before running the main method. Or it get executed at the time of class get loaded

817) Gets executed at the time of Object creation. Or it get executed only after creating a object of class

818) These blocks are used to initialize the static members (static variables) of class

819) These blocks are used to initialize the non-static members (instance variables) of class 820) These block get executed only

once for entire program execution

821) These block get executed when ever the new object is created

822) Inside static block static members can be accessed directly where as non static members should be accessed by using the reference of the object 823) 824) class StaticBlock 825) { 826) int a=23; 827) static int b=15; 828) 829) static { 830) System.out.println("Adding two number."); 831) 832) int sum=0; 833) sum = a +

b; //Error because a is non-static. b can be accessed because b is static

834) }

835)

836) }

837)

838) Inside the non-static block, both static and non-static members can be accessed directly 839) 840) 841) class InstanceBlock 842) { 843) int a=23; 844) static int b=15; 845) 846) { 847) System.out.println("Addition of two numbers..."); 848) int sum=0; 849) sum = a + b; //

no error because its non-static block

850) }

851)

852) }

853) Static block is called has static

initialization block (SIB)

854) Non-static block is called has instance initialization block (IIB)

855)

856) Difference between constructor and method

857) Constructor 858) Method

859) Name of constructor should be same has the class name

860) Name of method can be anything other than a class name

861) Constructor cannot be inherited 862) Method can be inherited 863) Constructor cant return anything 864) Method can return a value 865) By default the compiler will have a default

constructor

866) There is nothing called has default method 867) Constructor is used to initialize the

instance variables of class

(36)

869) 870) 871)

(37)

872) Method Overriding

873) Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class.

874)

875) A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding. The following example demonstrates method overriding.

876) 877) class Father 878) { 879) String name; 880) double height; 881) int age; 882) 883) void factory() 884) { 885) System.out.println("Parent factory()"); 886) } 887) void home() 888) { 889) System.out.println("some home()"); 890) } 891) } 892)

893) class Son extends Father

894) {

895)

896) void factory() //Son modifying Father factory() 897) {

898) System.out.println("modified Parent factory() by Son“); 899) }

900) void home() //Son modifying Father factory() 901)

902) {

903) System.out.println("modified Parent home() by Son");

904) }

905) }

906) public class Test {

907) public static void main(String[] args) {

908) Father f = new Son();

909)

910) f.factory(); //hear the Son's factory() is called, because Parent factory() is overridden by Son

911)

912) f.home(); //hear the Son's home() is called, because Parent home() is overridden by Son

913) }

914) }

915) 916)

(38)
(39)

918) Rules for method overriding:

 The argument list should be exactly the same as that of the overridden method.

 The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.

 The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overriding method in the sub class cannot be either private or protected.

 Instance methods can be overridden only if they are inherited by the subclass.  A method declared final cannot be overridden.

 A method declared static cannot be overridden but can be re-declared.  If a method cannot be inherited, then it cannot be overridden.

 A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.

 A subclass in a different package can only override the non-final methods declared public or protected.

 An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

 Constructors cannot be overridden.

919) Type Casting in JAVA

920) Java supports two types of castings – primitive data type casting and reference type casting. Reference type casting is nothing but assigning one Java object to another object. It comes with very strict rules and is explained clearly in Object Casting(next topic). Now let us go for data type casting.

921) a) data type casting

922) Java data type casting comes with 3 flavors. 1. Implicit casting

2. Explicit casting 3. Boolean casting.

(40)

923) 1. Implicit casting (widening conversion)

924) A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done implicitly by the JVM. The lower size is widened to higher size. This is also named as automatic type conversion.

925) class Vikas

926) {

927) public static void main(String[] args) { 928) 929) int a = 10; 930) double d = a; 931) System.out.println(d); //prints 10.0 932) 933) } 934) }

935) 2. Explicit casting (narrowing conversion)

936) A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM and requires explicit casting; a casting operation to be performed by the programmer. The higher size is narrowed to lower size.

937) class Vikas

938) {

939) public static void main(String[] args) { 940)

941) double d = 10.89;

942) int c = d ; //Error

943) double d = 10.89;

944) int c = d ; //Error

945) int a = (int)d; //explicit casting 946)

947) }

948) }

949) 3. Boolean casting

950) A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7 data types can be assigned to one another either implicitly or explicitly; but boolean cannot. We say, boolean is incompatible for conversion.

951) NOTE :

952) byte –> short –> int –> long –> float –> double

953) In the above statement, left to right can be assigned implicitly and right to left requires explicit casting. That is, byte can be assigned to short implicitly but short to byte requires explicit casting.

954) b) Reference type casting

 Subclass object can be assigned to a super class object and this casting is done implicitly. This is known as upcasting (upwards in the hierarchy from subclass to super class)

(41)

955) Eg : Father f = new Son();//implicit casting 956)

 Java does not permit to assign a super class object to a subclass object (implicitly) and still to do so, we need explicit casting. This is known as down casting (super class to subclass). Down casting requires explicit conversion. In down casting , first you need to do the upcasting after upcasting than only u can perform the down casting. Or else its a classCastException

957) Eg : Father f = new Son(); //upcasting 958) Son s = (Son) f; //down casting 959)

960) Son s = (Son) new Father(); //compiles but at runtime give exception 961) 962) 963) class Father 964) { 965) void factory() 966) { 967) System.out.println("Parent factory()"); 968) } 969) void home() 970) { 971) System.out.println("some home()"); 972) } 973) } 974)

975) class Son extends Father

976) {

977)

978) void factory() {

979) System.out.println("modified Parent factory() by Son");

980) }

981) void home()

982) {

983) System.out.println("modified Parent home() by Son");

984) }

985) void car()

986) {

987) System.out.println("Son alone has car()");

988) }

989)

990) }

991)

992) implicit casting (implicit UPCASTING) 993) public class Test {

994) public static void main(String[] args) 995) {

996) Father f = new Son();//implicit casting

997) f.factory();

998) f.home();

999) f.car(); //Error cant accesses Son class methods using parent reference

1000) }

1001) }

(42)

1003) public class Test {

1004) public static void main(String[] args) {

1005) Father f = new Son();// implicit casting

1006) Son s = (Son)f;

1007) s.factory();

1008) s.home();

1009) s.car(); //no error because the explicit casting is done

1010) }

1011) }

1012) So by explicit casting we can accesses the child class members using the parent class reference

1013) 1014)

(43)

1015) Abstract class

1016) An abstract class is a class that is declared with the abstract key word, it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be sub classed. Cant create the object of abstract class

1017) public abstract class Game 1018) {

1019) //abstract class without any methods 1020) }

1021)

1022) public abstract class Cade 1023) {

1024)

1025) abstract void draw(); 1026)

1027) //abstract class with abstract methods 1028) }

1029)

1030) abstract class Plan

1031) {

1032) void costEstimation()

1033) {

1034) //some code to tell about cost to build

1035) }

1036) abstract void baseMent(); 1037) abstract void build(); 1038)

1039) } //abstract class with concreate and abstract methods 1040)

1041) Whenever you inherit the abstract class you need to override the abstract methods of the abstract(PARENT) class in the inherited (CHILD) class. OR else you should declare the child class also has abstract class. See the example below

1042) Example : 1043) class Volvo 1044) { 1045) void body() 1046) { 1047) //code 1048) } 1049) void ac(); 1050) void music(); 1051) void seats(); 1052) } 1053)

1054) abstract class ElectricWork extends Volvo

1055) {

1056) void ac()

1057) {

1058) //code

(44)

1060) void music()

1061) {

1062) //code

1063) }

1064) }

1065) class KSRTC extends ElectricWork

1066) { 1067) void seats() 1068) { 1069) //code 1070) } 1071) } 1072)

Hear ElectricWork class is also abstract because all the abstract methods of Volvo class has not been overridden in this class, i.e seats() method is not overridden.

1073) KSRTC class has overridden all the parents class abstract methods so it need not to be abstract class

1074) Important Points about Abstract class

 abstract keyword is used to make a class abstract.

 Abstract class can’t be instantiated.

 We can use abstract keyword to create an abstract method, an abstract method doesn’t have body.

 If a class have abstract methods, then the class also needs to be made abstract using abstract keyword, else it will not compile.

 Its not necessary to have abstract classes to have abstract method.

 If abstract class doesn’t have any method implementation, its better to use interface because java doesn’t support multiple class inheritance.

 The subclass of abstract class must implement all the abstract methods unless the subclass is also an abstract class.

 Abstract classes can implement interfaces without even providing the implementation of interface methods.

 Abstract classes are used to provide common method implementation to all the subclasses or to provide default implementation.

 Abstract class can have a constructor but it can be called from the child class using supper statement

 We can run abstract class like any other class if it has main() method.

 In interview give some good examples like bank or google example (refer class notes) 1075) Example1:

(45)

1076) {

1077) void playSong(String songName)

1078) {

1079) System.out.println(songName+" is playing in the player");

1080) }

1081) abstract void pauseControle(); 1082) abstract void screenControler();

1083) }

1084)

1085) class Windows extends MediaPlayer

1086) {

1087) void pauseControle()

1088) {

1089) System.out.println("Press P to pause the song");

1090) }

1091) void screenControler()

1092) {

1093) System.out.println("Do changes using menu button");

1094) }

1095) }

1096)

1097) class VLC extends MediaPlayer

1098) {

1099) void pauseControle()

1100) {

1101) System.out.println("Press space-bar to pause the song");

1102) }

1103) void screenControler()

1104) {

1105) System.out.println("Press A to change the screen size");

1106) }

1107) }

1108)

1109) Interface

 Interface in java is one of the way to achieve 100% abstraction in Java .

 Interface in java is declared using keyword interface. It is also just like normal class. For interface also the .class file is going to be generated.

 All methods inside interface are public by default

 All variables declared inside interface is implicitly public final variable or constants. 1110) interface Office

1111) {

1112) int employee;//Error because only final variables so they need to be initialised has donoted in below example. No other types are allowed inside interface

1113) }

1114) interface Office

(46)

1116) int employee=100;

1117) }

 All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword

 Cant create the Object of interface

 In Java its legal for an interface to extend multiple interface. for example following code will run without any compilation error

1118) package com.vikas.jspiders; 1119) interface Animal

1120) {

1121) public void eat();

1122) public void walk();

1123) }

1124) interface Human

1125) {

1126) public void talk();

1127) public void work();

1128) }

1129) interface Livingbeing extends Animal,Human // extend multiple interface

1130) {

1131) public void enjoyWithLover();

1132) }

1133) Whenever we implement interface we need to provide implementation to all the abstract methods of it, or else we need to make the inherited class also has abstract.

1134) interface Office

1135) {

1136) void work();

1137) public void enjoy();

1138) }

1139) abstract class Manager implements Office

1140) {

1141) //implementation is not give for work() and enjoy() so class should be abstract 1142) } 1143) 1144) Example:-1145) interface Animal 1146) {

1147) public void eat();

1148) public void walk();

1149) }

1150) interface Human

1151) {

1152) public void talk();

1153) public void work();

1154) }

1155) interface Livingbeing extends Animal,Human

1156) {

1157) public void enjoyWithLover();

1158) }

1159) public class Test implements Livingbeing{ 1160)

(47)

1161) public void eat() 1162) {

1163) // TODO Auto-generated method stub

1164) }

1165) public void walk()

1166) {

1167) // TODO Auto-generated method stub

1168) }

1169) public void talk() 1170) {

1171) // TODO Auto-generated method stub

1172) }

1173) public void work()

1174) {

1175) // TODO Auto-generated method stub

1176) }

1177) public void enjoyWithLover() 1178) {

1179) // TODO Auto-generated method stub

1180) }

1181)

1182) }

1183)

1184) The Interface reference can be give to its child class object. It behave same has the inheritance. Using the interface reference we cant accesses the child class members. But we can accesses the overrided methods.

1185)

1186) Example: 1187)

1188) interface Animal

1189) {

1190) public void eat();

1191) public void walk();

1192) }

1193)

1194) class Cow implements Animal

1195) {

1196)

1197) public void eat()

1198) {

1199) System.out.println("Cow eat hullu");

1200) }

1201)

1202) public void walk()

1203) {

1204) System.out.println("Cow walk in four legs");

1205) }

1206) public void giveMilk()

1207) {

1208) System.out.println("Cow give white milk");

1209) }

1210)

1211) }

1212) class Test1

1213) {

(48)

1215)

1216) Animal a = new Cow();

1217) a.eat();

1218) a.walk();

1219) a.giveMilk();//Error because parent reference cant accesses child members 1220) } 1221) } 1222) 1223) 1224) Abstract 1225) Interface 1226) Multiple Inheritance 1227) A class can inherit only one Abstract Class 1228) A class can implement multiple Interfaces 1229) Concrete methods (Default Behavior) 1230) In abstract class you can provide default behavior of a method, so that even if child class does not provide its own behavior, you do have a default behavior to work with

1231) You cannot provide a default behavior in interfaces. Interfaces only allow you to provide

signature of the method

1232) Access Modifiers

1233) You can provide access

modifiers to methods in abstract classes (static , final, etc) 1234) You cannot provide access modifiers methods in Interfaces. 1235)

1236) Methods and variables

1237) The methods or variables can be declared with any accesses specifiers and modifiers. (Note : but abstract methods should not be static , final, private) 1238)

1239) All methods are public by default, all the variables are static final by default. 1240)

1241)

1242) Abstraction

1243) abstraction in Java is used to hide certain details and only show the essential features of the object.

1244) Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.

1245) Abstraction lets you focus on what the object does instead of how it does it.

1246)We are going to achieve abstraction using

1247) Abstract class

1248) Interface

1249)

References

Related documents

Da, Decentralized sliding mode adaptive controller design based on fuzzy neural networks for interconnected uncertain nonlinear systems, IEEE Trans. Morris, Fuzzy neural networks

The ABC Program uses an automated self-service-based border clearance kiosk solution (the “ABC System”) to partially automate the processing of eligible travellers

Transmission or copying of this document is not permitted without prior written authorization. The wording &#34;Document Alcatel Business Systems&#34; must appear on all

Mercer county records search new jersey police arrest order for law for individuals in camden county nj public records in court and available.. Looking for sure your favorite

I conducted in -depth interviews with eight women who identify as either survivors or victims of Domestic violence and are African born, I also interviewed two administrators of local

Yet, within music’s industrial production cultures, a dismissive postfeminist sensibility has come under pressure through a reflexive critical moment of popular

Among both those visitors who had visited a museum in San Antonio in the past 12 months or planned to do so in the next six, seeing friends or relatives as well as going to

The present work evaluates the nutritional and feed value of fermented sweet potato meal (ProEn-K TM ) to replace soybean meal in the diet of juvenileP.