forked from rahulXbarnwal/JavaTutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVehicle.java
More file actions
57 lines (43 loc) · 1.58 KB
/
Vehicle.java
File metadata and controls
57 lines (43 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package oops2;
public class Vehicle {
int wheelsCount;
String model;
void start() {
System.out.println("Vehicle is starting");
}
Vehicle() {
System.out.println("Creating a vehicle instance");
}
Vehicle(int wheelsCount) {
this.wheelsCount = wheelsCount;
System.out.println("Creating vehicle with wheels");
}
// a constructor can't have a return type
// if you add a return type, java treats it as normal method, not a constructor
// void Vehicle() {
// System.out.println("bye");
// }
// valid constructor
// by default access modifier of a constructor is package-private (also called default access)
// Vehicle() {
// System.out.println("This is constructor");
// }
// constructors can have access modifier -> public, protected, default, private
// public constructor -> object can be created from anywhere
// public Vehicle() {}
// default (package-private) -> object can be created only within same package
// Vehicle() {}
// protected constructor
// ✔ Same package
// ✔ Subclasses in other packages
// ❌ Other classes
// protected Vehicle() {}
// private constructor
// ❌ Cannot create object using new from outside
// Used for: Singleton pattern, Utility classes, Factory methods
// private Vehicle() {}
// Constructor can't be final, static or abstract
// why not final -> cannot override (constructors are not inherited)
// why not static -> constructor belongs to object not a class
// why not abstract -> constructor must have a body
}