as we know a static method could access static data and
static method only. then how could main method call the
object of aclass which is not static and other non static data

Answer Posted / ramya

though main method is static, it can access non-static
(instance) variabels or methods by creating an instance of
the class in which the variables and methods are..
Example:
class LessonTwoB {

String text = "I'm a Simple Program";
static String text2 = "I'm static text";

String getText(){
return text;
}

String getStaticText(){
return text2;
}

public static void main(String[] args){
LessonTwoB progInstance = new LessonTwoB();
String retrievedText = progInstance.getText();
String retrievedStaticText =
progInstance.getStaticText();
System.out.println(retrievedText);
System.out.println(retrievedStaticText);
}
}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How to run a JAR file through command prompt?

710


Why constructor has no return type?

634


What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

619


What do you mean by stream pipelining in java 8?

732


Name few java util classes introduced with java 8 ?

495






What is the difference between static and global variables and also define what are volatile variables?

547


Explain about features of local inner class?

597


Can we restart a dead thread in java?

546


Difference between Linked list and Queue?

602


Why is string builder not thread safe?

587


What is a treeset class?

550


In which order the iterator iterates over collection?

575


When to use runnable interface vs thread class in java?

514


Can arraylist contain null values?

562


What does exp mean in math?

526