Accessing Non-Static Members in Java: Instance Variables and Methods

Day 21 – Accessing Non-Static Members of a Class in Java Yesterday I explored static members in Java. Today’s concept was the opposite side of it: 👉 Non-Static Members (Instance Members) Unlike static members, non-static members belong to objects, not the class itself. That means we must create an object of the class to access them. 🔹 Syntax new ClassName().memberName; or ClassName obj = new ClassName(); obj.memberName; 🔹 Example class Demo4 { int x = 100; int y = 200; void test() { System.out.println("running test() method"); } } class MainClass2 { public static void main(String[] args) { System.out.println("x = " + new Demo4().x); System.out.println("y = " + new Demo4().y); new Demo4().test(); } } Output x = 100 y = 200 running test() method 🔹 Important Observation Every time we write: new Demo4() ➡️ A new object is created. Each object has its own copy of non-static variables. This is why instance variables are object-specific, unlike static variables which are shared across objects. 📌 Key takeaway • Static members → belong to the class • Non-static members → belong to objects • Accessing instance members requires object creation Understanding this concept is essential for mastering Object-Oriented Programming in Java. Step by step building stronger Core Java fundamentals. #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories