Java Class Methods

Java Class Methods

Class methods are functions defined inside a class that describe the behavior or actions of objects. They operate on class attributes or perform specific tasks.


1. Method Syntax


  • modifierpublic, private, static, etc.

  • returnType → data type of value returned (void if nothing is returned)

  • methodName → name of the method

  • parameters → optional input values


2. Example 1: Instance Method


 

📌 Output:

Brand: Toyota, Year: 2022
Brand: Honda, Year: 2023

Instance methods operate on instance variables and require objects to be called.


3. Example 2: Static Method


 

📌 Output:

Sum = 15

Static methods belong to the class, not the object, and can be called using the class name.


4. Example 3: Method with Parameters and Return Value


 

📌 Output:

Product = 20

5. Example 4: Method Calling Another Method


 

📌 Output:

Hello, Alice
Welcome!

6. Key Points About Class Methods

FeatureInstance MethodStatic Method
Belongs toObjectClass
Access instance variables?YesNo (only static variables)
Call syntaxobject.method()Class.method()
Can be overriddenYesNo (cannot override static methods)
  • Methods define object behavior.

  • Instance methods need objects; static methods do not.

  • Methods can have parameters and return values.

You may also like...