Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with Code.. Help with Classes

 
Avin Sinanan
Ranch Hand
Posts: 109
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok examine the code.. its now long..actually its very simple.. read it and i will tell you the problem i am having...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
class StringClass
{
public static void main(String[] args)
{
int age ;
Class1 firstClass = new Class1();
age =firstClass.method1();
System.out.println("my grandfather is" + age + "old");
}
}
class Class1
{
int fatherAge ;
int grandFatherAge;
public Class1()
{
}
public int method1()
{
/*Lets assume that a textField appears at this point and the user
is allowed to type in fatherAge..lets assume in this case they typed
in 30. Now this means grandFatherAge is highly variabele and grandFatherAge
depends on fatherAge.*/

fatherAge = 30;
grandFatherAge = fatherAge + 25 ;
return grandFatherAge ;
}
}
class Class2
{
public Class2()
{
/* I would like to know how to print grandFatherAge in class2*/
System.out.println("My Grandfather died at" + grandFatherAge);
}
}

Now look at Class2... how am i suppose to print grandFatherAge?
The problem with granfatherAge is that i must print it in class2
and the values must be produced in Class1.
Now I cannot use the line of code in Class2
Class1 secondClass = new Class1();
int grand = secondClass.method1();
System.out.println("My Grandfather died at" + grand);
because i had to create another Class1 called secongClass and this class does not conatin the original value typed ib first (ie. 30)
How do i print at what age my grandfather died. Now i have to keep all three classes i cannot take away any classes because this is bacsically a simplication of a very complex project i am working on.
Is there some kind of getmethod that i can use.. and also remeber Class2 had to regognise the class "firstClass".
thanks...
 
Dave Vick
Ranch Hand
Posts: 3244
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avin
Since grandfatherAge is an instance variable you'll need to have an instance of class1 in order to access it. The first question is what is the relation between class1 and class2? How do they work together or are they completely unrelated? The simplest way would be to have an instance variable in class2 that is a class1 object, then each instance of class2 would have an instance of class1 and could access all of its public variables through that instance.
hope that helps
Dave
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic