Lesson 30 of 34

static और final

8 min 35 XP

static field सभी objects में साझा होता है, उसकी सिर्फ़ एक copy होती है, जैसे यह गिनने के लिए कि कितने objects बने। static method को object के बिना ClassName.method() से call करें। final value बदली नहीं जा सकती।

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

main() static क्यों है? क्योंकि JVM को उसे किसी भी object के बनने से पहले call करना होता है। Interview का लोकप्रिय सवाल।

Challenge

+35 XP

class Counter लिखें जिसमें एक static int total और हर object का अपना int value हो। increment() दोनों में 1 जोड़ता है। main() में n पढ़ें, दो Counters बनाएँ, पहले को n बार और दूसरे को दो बार increment करें, फिर print करें: Input: 3 Output: A: 3 B: 2 Total: 5

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.