|
510 | 510 |
|
511 | 511 | * **What is the difference between a constructor and a method?**
|
512 | 512 | - Constructor and a method they both run a block of code but the difference is in calling them.
|
513 |
| - - 1) Constructor gets called automatically when we create an object of that class, we cannot call it explicitly |
514 |
| - though we can call parent class constructor using 'super' keyword. |
515 |
| - - 1) We call method directly using their name. |
516 |
| - - 2) Constructor Syntax - |
517 |
| - |
| 513 | + - Constructor gets called automatically when we create an object of that class, we cannot call it explicitly |
| 514 | + though we can call parent class constructor using 'super' keyword. |
| 515 | + - We call method directly using their name. |
| 516 | + - Constructor Syntax - |
518 | 517 | public class SomeClass{
|
519 |
| - |
520 |
| - SomeClass(parameter_list){ |
521 |
| - ... |
522 |
| - } |
523 |
| - |
| 518 | + SomeClass(parameter_list){ |
| 519 | + ... |
| 520 | + } |
524 | 521 | ...
|
525 |
| - |
526 | 522 | }
|
527 |
| - |
528 | 523 | Note:
|
529 | 524 | Constructor name is the same as class name
|
530 | 525 | Constructor does not have return type
|
531 | 526 |
|
532 |
| - -2) Method Syntax - |
533 |
| - |
| 527 | + - Method Syntax |
534 | 528 | public class SomeClass{
|
535 |
| - |
536 |
| - public void someMethod(){ |
| 529 | + public void someMethod(parameter_list){ |
537 | 530 | ...
|
538 | 531 | }
|
539 | 532 | // call method
|
540 |
| - someMethod() |
| 533 | + someMethod(parameter_list) |
541 | 534 | }
|
542 | 535 |
|
543 | 536 | - Name of the method can be anything.
|
544 |
| - - When you make an object of a class, then the constructor of that class will be called automatically. But for methods, we need to call it explicitely. |
| 537 | + - When you make an object of a class, then the constructor of that class will be called automatically. |
| 538 | + But for methods, we need to call it explicitely. |
545 | 539 | - Constructors can't be inherited but you can call the constructor of the parent class by calling `super()`.
|
546 | 540 |
|
547 | 541 | * **Differences between abstract classes and interfaces?**
|
|
0 commit comments