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

Can a java program have 2 main methods?

549


Can we sort set in java?

542


Is there a case when finally will not execute?

569


What is the protected method modifier?

563


Tell me about different OOPS concepts.

593






What about main thread in java?

652


Write a program to show whether a graph is a tree or not using adjacency matrix.

596


What is the difference between sleep and wait in java?

514


What is string variable?

569


How can you write a loop indefinitely in java programming?

554


How do you use compareto method?

534


What is meant by 'Class access modifiers'?

554


why are wait(), notify() and notifyall() methods defined in the object class? : Java thread

555


How to find the index of the largest number in an arraylist java?

520


What is object cloning in Java?

636