← Back to Scala Course | Chapter 7: OOP Basics | Lesson 3 of 7

Fields और Methods

Fields वे facts हैं जो एक object याद रखता है और methods वे चीज़ें हैं जो वह कर सकता है, जैसे एक dog जिसका एक नाम हो और जो bark कर सके। constructor inputs में val या var जोड़ने से वे fields बन जाते हैं।

In this page:

  1. Fields and Methods
Syntax
scala
class ClassName(val field1: Type, var field2: Type) {
  def method_name(param: Type): ReturnType = {
    // body
  }
}

Fields and Methods

किसी constructor parameter से पहले val या var जोड़ना, जैसे class Point(val x: Int, val y: Int), उसे instances पर एक public, read-only (या mutable, var के लिए) field के रूप में उजागर करता है।

Methods को class body के अंदर def से define किया जाता है और वे इन fields को सीधे access कर सकते हैं। val/var के बिना, एक constructor parameter सिर्फ class body के अंदर उपयोग होता है, बाहर से access नहीं होता।

Note: val/var के बिना एक constructor parameter class body के लिए private होता है -- इसे public field के रूप में उजागर करने के लिए val जोड़ें।

उदाहरण: Fields and Methods

markup
class Rectangle(val width: Int, val height: Int) {
  def area(): Int = width * height
}

object Main extends App {
  val rect = new Rectangle(4, 5)
  println(rect.width)
  println(rect.area())
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. class Point(x: Int) declare करना और p.x access करना, जो fail हो जाता है क्योंकि val के बिना parameter एक public field नहीं है।
  2. def area = width * height() लिखना जिसमें parentheses styles मिल जाती हैं, जबकि () से defined method को () से call किया जाता है।
  3. rect.width = 10 जैसे किसी val field को assign करने की कोशिश करना, जबकि reassignable होने के लिए इसे var चाहिए।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.