2012-02-02 149 views
-6

我有一个主要的类,用户输入数据后,我想去另一个类。我不知道如何去下一个类,并继承java代码中的值x和y。类继承java

public class main { 
        int x=25; 
        int y =25; 
        //Go to next class second 
        } 

public class second { 
        //inherit values of x and y 
        //manipulate values 
        //Go to next class third 
        } 

public class third { 
        //inherit values of x and y from second class 
        //manipulate values 
        } 
+1

请阅读[this](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)。 – mre 2012-02-02 15:41:20

回答

-1
public class Main { 
        int x=25; 
        int y =25; 
        //Go to next class second 
        aMethod(){ 
        Second s = new Second(); 
        s.manipulateValues(x,y); 
        } 
        } 

public class Second { 
        //inherit values of x and y 
        //manipulate values 
        //Go to next class third 
         public void manipulateValues(int x, int y){ 
          //manipulate here 
          Third t = new Third(); 
          s.manipulateHereToo(x,y); 
         } 
        } 

public class Third { 
        //inherit values of x and y from second class 
        //manipulate values 
         public void manipulateHereToo(int x, int y){ 
          //manipulate again 
         } 
        } 

所以你无须使用继承。

+0

一旦用户输入了值,我该如何转到第二类? – Simon 2012-02-02 15:43:23

+0

您创建一个类型为Second的实例,并调用您感兴趣的方法,传递两个参数(x和y)。 – tartak 2012-02-02 15:46:47

+0

那么downvote是怎么回事?:) – tartak 2012-02-02 15:54:18

0
public class second extends main{ 
        //inherit values of x and y 
        //manipulate values 
        //Go to next class third 
        } 

public class third extends main{ 
        //inherit values of x and y from second class 
        //manipulate values 
        } 
0

您可以从另一个类使用extends关键字继承。

public class First { 
    int x = 25; 
    int y = 25; 
} 
//Class Second inherits (extends) from class First. 
//This class will inherit from First, all its values (x and y). 
public class Second extends First { 
    public Second() { 
     //Here we change the values of x and y in Second's constructor. 
     x = 26; 
     y = 26; 
    } 
} 
+0

来自主类如果用户输入了值,我该如何去第二类? – Simon 2012-02-02 15:44:53

+0

@Simon你是什么意思“去”? – 2012-02-02 16:01:54

2

我不认为你的意思是在这里继承。你只是想通过这些值来做其他类来对它们进行计算吗?

如果你确实意味着继承,为了构建已经给出的另一个答案,你可能想要像这样修改它。

public class second extends main{ 
        //inherit values of x and y 
        //manipulate values 
        //Go to next class third 
        } 

public class third extends second{ 
        //inherit values of x and y from second class 
        //manipulate values 
        } 
+0

是的我试图从主类传递x和y的值 – Simon 2012-02-02 15:41:23

3

您描述的问题与继承无关。 解决方案似乎是一个两步骤的过程。

  1. Learn Java
  2. 将所需的值作为参数传递给方法调用。
+0

我是刚刚开始,感谢您的链接:) – Simon 2012-02-02 15:46:23