Skip to content

Commit f7c53cd

Browse files
committed
feat: Demonstrate static variables and static methods using Mobile1 class [static-method-variable-demo]
🔑 Key: static-method-variable-demo 🧠 Logic: - `Mobile1.name` is a static variable → shared by all instances of the class. - `brand` and `price` are instance variables → unique for each object. - `show()` is a non-static method → accesses both instance and static variables. - `show1()` is a static method → can only access static members directly but can use object reference to access instance members. 📌 Concepts Illustrated: - 📌 **Static Variable**: • Declared as `static String name;` • Shared among all instances. Changes to `Mobile1.name` reflect in all objects. • Example: Changing `Mobile1.name = "SmartPhone";` affects both `obj1` and `obj2`. - 📌 **Instance Variables**: • `brand` and `price` are specific to each object. - 📌 **Static Method**: • Can’t access non-static variables directly (e.g., `brand`, `price`). • Accepts an object as parameter (`Mobile1 obj`) to access instance members. 🧪 Output: - obj1: Apple : 1500 : SmartPhone - obj2: Samsung : 1700 : SmartPhone - show1(obj1): Apple : 1500 : SmartPhone 🧠 Note: - If `name` were non-static, each object could have a different name. - Static methods are typically used for utility or class-wide operations, not tied to object state. Signed-off-by: Somesh diwan <[email protected]>
1 parent 2ed49cd commit f7c53cd

File tree

1 file changed

+3
-5
lines changed

1 file changed

+3
-5
lines changed

Section10Methods/LocalandGlobalVariables/src/StaicMethodDemo.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,14 @@ public void show() {
99
System.out.println(brand+" : "+price+" : "+name);
1010
}
1111

12-
public static void show1(Mobile1 obj)
13-
{
12+
public static void show1(Mobile1 obj) {
1413
// System.out.println("in static method");
1514
System.out.println(obj.brand+" : "+ obj.price +" : "+obj.name);
1615
}
1716
}
1817

1918
public class StaicMethodDemo {
20-
public static void main(String[] args)
21-
{
19+
public static void main(String[] args) {
2220
Mobile1 obj1=new Mobile1();
2321
obj1.brand="Apple";
2422
obj1.price=1500;
@@ -41,4 +39,4 @@ public static void main(String[] args)
4139

4240
//System.out.println(obj1.brand);
4341
}
44-
}
42+
}

0 commit comments

Comments
 (0)