Make 3 classes call one another - java

So I'm trying to figure out how can I have 3 classes call one another.
this is the main class.
public class TestStudent {
public static void main(String[] args) {
myStudent mystudent_obj = new myStudent();
mystudent_obj.show_grades();
mystudent_obj.change_grades();
mystudent_obj.show_grades();
}
}
This is the 2nd class that's being called in the class above;
The 2nd class call another 3rd class and try to manipulate it
using two functions. Function show_grades just print out the variables in the 3rd class
and function change_grade try to change the variables in the 3rd class.
public class myStudent {
public void show_grades(){
Student student_obj = new Student();
System.out.println(student_obj.studGrade);
System.out.println(student_obj.studID);
}
public void change_grades(){
Student student_obj = new Student();
student_obj.studGrade='V';
student_obj.studID=10;
}
}
This the 3rd call, which only has two variables.
public class Student {
public int studID = 0;
public char studGrade = 'F';
}
when I run the program it runs without errors and I get an output of:
F
0
F
0
however, I can see that the function show_grades work and it does display the grades, but
the function change_grades does not change the grades:
The end results, should be something like this
F
0
V
10
because the change grade function, should have changed those variables... so what's going on?

In your myStudent class you are creating a new instance of Student in each method, meaning that each method has a local variable of class Student. When you call show_grades the second time, a new instance is created, with the default values of 0 and F.
If you create a variable and use that instead, your change grades will change the variables of the instance variable instead of a local variable in each method. This is due to scoping in programming, which you can read more about at Wikipedia.
public class myStudent {
private Student student_obj = new Student();
public void show_grades() {
System.out.println(student_obj.studGrade);
System.out.println(student_obj.studID);
}
public void change_grades(){
student_obj.studGrade='V';
student_obj.studID=10;
}
}

Related

what is the name of such invocation "variable.methodName(data);" ? [duplicate]

See the code snippets below:
Code 1
public class A {
static int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
short s = 9;
System.out.println(add(s, 6));
}
}
Code 2
public class A {
int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
A a = new A();
short s = 9;
System.out.println(a.add(s, 6));
}
}
What is the difference between these code snippets? Both output 15 as an answer.
A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();
Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:
MyClass.myMethod();
this.myMethod();
myMethod();
Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:
MyClass boston = new MyClassConstructor();
boston.myMethod("bostonURL");
MyClass miami = new MyClassConstructor();
miami.myMethod("miamiURL");
MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");
In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.
If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.
Generally
static: no need to create object we can directly call using
ClassName.methodname()
Non Static: we need to create a object like
ClassName obj=new ClassName()
obj.methodname();
A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
Reference:Static Vs Non-Static methods
Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.
A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.
In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.
Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -
A static method belongs to the class and a non-static method belongs to an object of a class.
I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
Now output will be:::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:
If your method is related to the object's characteristics, you should define it as non-static method. Otherwise, you can define your method as static, and you can use it independently from object.
Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();
Basic difference is non static members are declared with out using the keyword 'static'
All the static members (both variables and methods) are referred with the help of class name.
Hence the static members of class are also called as class reference members or class members..
In order to access the non static members of a class we should create reference variable .
reference variable store an object..
Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.
Another scenario for Static method.
Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.
Here, we have private constructor and using static method we are creating a object.
Ex::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
Demo obj1 = Demo.createObj();
Here, Only 1 instance will be alive at a time.
- First we must know that the diff bet static and non static methods
is differ from static and non static variables :
- this code explain static method - non static method and what is the diff
public class MyClass {
static {
System.out.println("this is static routine ... ");
}
public static void foo(){
System.out.println("this is static method ");
}
public void blabla(){
System.out.println("this is non static method ");
}
public static void main(String[] args) {
/* ***************************************************************************
* 1- in static method you can implement the method inside its class like : *
* you don't have to make an object of this class to implement this method *
* MyClass.foo(); // this is correct *
* MyClass.blabla(); // this is not correct because any non static *
* method you must make an object from the class to access it like this : *
* MyClass m = new MyClass(); *
* m.blabla(); *
* ***************************************************************************/
// access static method without make an object
MyClass.foo();
MyClass m = new MyClass();
// access non static method via make object
m.blabla();
/*
access static method make a warning but the code run ok
because you don't have to make an object from MyClass
you can easily call it MyClass.foo();
*/
m.foo();
}
}
/* output of the code */
/*
this is static routine ...
this is static method
this is non static method
this is static method
*/
- this code explain static method - non static Variables and what is the diff
public class Myclass2 {
// you can declare static variable here :
// or you can write int callCount = 0;
// make the same thing
//static int callCount = 0; = int callCount = 0;
static int callCount = 0;
public void method() {
/*********************************************************************
Can i declare a static variable inside static member function in Java?
- no you can't
static int callCount = 0; // error
***********************************************************************/
/* static variable */
callCount++;
System.out.println("Calls in method (1) : " + callCount);
}
public void method2() {
int callCount2 = 0 ;
/* non static variable */
callCount2++;
System.out.println("Calls in method (2) : " + callCount2);
}
public static void main(String[] args) {
Myclass2 m = new Myclass2();
/* method (1) calls */
m.method();
m.method();
m.method();
/* method (2) calls */
m.method2();
m.method2();
m.method2();
}
}
// output
// Calls in method (1) : 1
// Calls in method (1) : 2
// Calls in method (1) : 3
// Calls in method (2) : 1
// Calls in method (2) : 1
// Calls in method (2) : 1
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances

Objects of multiple class in java

I was revising some of the old school concepts of Java in order to solve one problem . I have written the following code where i am trying the create objects of multiple class in that same classes and calling the methods with those objects from the main.
class a {
public void display() {
System.out.println("inside class a");
a a1= new a();
}
}
class b {
public void display() {
System.out.println("inside class b");
b b1= new b();
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a1.display();
b1.display();
o.display();
}
}
I am getting object cannot be resolved error. My question is what i need to change to let the above code work. And, do i need to always declare objects inside the main().
Any help will be highly appreciated
I'm not really sure why you would want to do that, but assuming you're just wondering about the possibility to implement such a thing - yes, it can be done.
You can create an instance of a class inside that same class, like so:
public class A {
public static A instance = new A();
public void display() {
System.out.println("inside class A");
}
}
Pay attention to the static modifier in the above code; it allows you now to access instance from another place (class, method, main) like so:
A.instance.display();
If you want to know whether you can declare a variable inside a method, and not a class, and make it accessible from another method, then the answer is - no, you cannot.
Yes you need to declare objects inside the main()
class a {
public void display() {
System.out.println("inside class a");
}
}
class b {
public void display() {
System.out.println("inside class b");
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
a a1= new a();
b b1= new b();
one o = new one();
a1.display();
b1.display();
o.display();
}
}
Don't know what you want to achieve and yes you should create object of class a and class b inside main functions to use instance methods of these classes.
package com.stack.overflow;
class a
{
public void display()
{
System.out.println("inside class a");
//a a1= new a(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
class b
{
public void display()
{
System.out.println("inside class b");
//b b1= new b(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
public class one
{
void display()
{
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a a1=new a();
b b1=new b();
a1.display();
b1.display();
o.display();
}
}
You may find the answer to your confusion easily - #ratul-sharker : a1 & b1 must be declared and instantiated inside the main. as well as other answers here correcting your code.
The real question is your notion of scoping and lifetime of variables - Not only a1 and b1 lie inside the classes a and b but they have been instantiated inside methods so they are local. So, try to understand the difference between field variables and local variables - their lifetimes and scopes are vastly different.
Accessing a local variable directly like that(which will be instantiated when the method is called) is like asking asking for a result from future in the present. Note that field variables will remain as long as object is alive but the local variables will remain only for the duration of the method call.
Hope it is clear to you now.
Also, your question:
My question was is it possible to create an object of an class in the
same class and call it from main?
Yes. Because main is a static method so it is not bound to an object like non-static method does. static methods are class level while non-static methods are object level. You can also create an instance in a non-static method for that matter.

Trouble using a public attribute in java

I have just started coding in java and am trying to wrap my head around classes.
I seem to be having trouble using a public attribute in another class. I have 3 classes: one contains the main method; and the other 2 are input and output. I am using non-static variables and methods and I don't want to use static.
Even though I have instantiated the input class in the output class, the output class fails to recognize the public attribute. Why is that so?
Here are the 3 classes:
package random;
import java.util.Scanner;
import java.util.Arrays;
public class random
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your first name: ");
input inputObject = new input();
inputObject.setFirstName();
output outputObject = new output();
outputObject.getFirstName();
}
}
package random;
import java.util.Scanner;
public class input
{
public String firstName;
public input() {}
public void setFirstName() {
Scanner keyboard = new Scanner(System.in);
this.firstName = keyboard.nextLine();
}
}
package random;
import java.util.Scanner;
public class output
{
public void getFirstName()
{
input inputObject = new input();
System.out.println("Your first name is " + inputObject.firstName);
}
}
The input object created in the getFirstName method in the output class is a separate instance from the one created in your main method. This means essentially you are creating a new instance of input where the input isn't set for firstName yet so when you print out that property there is nothing to print.
In addition the get and set methods for a single property should be inside the same class. The general way of doing this is like this:
class Foo {
private String property = "";
Foo () {}; //empty default constructor
//sets the property to what is passed in as a parameter
public void setProperty(String newProperty) {
this.property = newProperty;
}
//returns the property
public String getProperty() {
return this.property;
}
}
Generally all class properties should be private with public setters and getters. If you are new to programming I suggest reading up on this more.
It's because you're using two different input objects. We can tell this because your program has the following line twice
input inputObject = new input();
The input object you assign a name to is a different object from the one you try to read the name from.
It makes no sense for the class output to exist at all. You should just have a method getFirstName() in the input class.
(Also class names in Java usually begin with a capital letter.)

Why do print statements execute in this order when using initializers, constructors and method calls?

This is the code I'm running , the output of this code is 4 2 1 3 , could someone please explain why the result was printed in this order.
public class goFuncTest {
goFuncTest()
{
System.out.print("1 ");
}
{
System.out.print("2 ");
}
public static void main(String[] args)
{
new goFuncTest().go();
}
void go()
{
System.out.print("3 ");
}
static
{
System.out.print("4 ");
}
}
Based on your recent question edit, your output will be 4 2 1 3. The static initializers are run first, then the instance initializers. If you had multiple initializers of the same type, they would execute in the order they appear in the class.
// static initializer first
static {
System.out.print("4 ");
}
// then instance initializer
{
System.out.print("2 ");
}
Next the constructor fires up, which gives you:
goFuncTest()
{
System.out.print("1 ");
}
finally the method is invoked:
void go()
{
System.out.print("3 ");
}
As JB Nizet pointed out in first comment, result should be 2,4,3,1.
And coming to the order, static blocks executes first and then initialization blocks. In your code there are no static blocks and only inti blocks.
The order of initialization block execution is the order they placed in source code -2,4.
And remaining two results as per constructor and method call. 1,3
Now you can see the answer right ?
Reason:
You have instance block which gets executed in sequence in which appear in your class definition. So 2 comes first and then 4 and hence output 2 4
Next you are calling new goFuncTest(), which is going to call your constructor and hence you will see 1 in the output.
Now on your instance you are calling go method which prints 3.
It seems the main confusion is just due to not understanding the various blocks that a class can have;
this answer gives a nice example and explanation;
Here's the code they give:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized).
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs before the constructor each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
This class has a static initialiser, an instance initialisation block, a constructor, and a class method.
static initialiser: static {...}
instance initialiser: {...}
constructor: Public ClassName(){...}
class method: Public Static Whatever classMethod(String[] args){...}
Each of these is called under different circumstances; the static initialiser is called when the class is loaded, there's no other way to call it, you can't even do it via reflection, as it's never represented by a method instance, it is called by the JVM.
the instance initialiser is called whenever you create an instance of the class - before the constructor.
You can have multiple static initialisers, and multiple instance initialisers, and they are executed in the order they appear in the code.
constructor and class method you presumably already know about.
In your example, it would probably be a little more helpful to rearrange the code slightly, to better reflect that hierarchy;
public class goFuncTest {
//static instance initialiser
static {
System.out.print("4 ");
}
//instance initialiser
{
System.out.print("2 ");
}
//Constructor
goFuncTest(){
System.out.print("1 ");
}
//Class method
void go(){
System.out.print("3 ");
}
public static void main(String[] args){
new goFuncTest().go();
}
}
(editted to add in the static keyword)

The Error "No Closing Instance..." [duplicate]

This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 8 years ago.
I am new at Java and lately I study class and object topics. However, I could not progress of this code:
public class ClassStudy {
// Student Group
class Student {
public String name = null;
public String surname = null;
boolean study(boolean does) {
// He studies.
boolean d = does;
return d;
}
boolean slackOff(boolean does) {
// He slacks off.
boolean d = does;
return d;
}
}
// Teacher Group
class Teacher {
public String name = null;
public String surname = null;
boolean teach(boolean does) {
// He teaches.
boolean d = does;
return d;
}
boolean learn(boolean does) {
// He learns.
boolean d = does;
return d;
}
}
// Main Method
public static void main(String[] args) {
Student student = new Student();
Teacher teacher = new Teacher();
}
}
In main method, I got errors of student, yet did not got of teacher. I do not know if I have done any mistake or I can not see it. What has to be done?
The errors I get:
The value of the local variable student is not used
No enclosing instance of type ClassStudy is accessible. Must
qualify the allocation with an enclosing instance of type ClassStudy
(e.g. x.new A() where x is an instance of ClassStudy).
Line breakpoint:ClassStudy [line: 44] - main(String[])
Either make the Student (and Teacher) class static or make it a top level class
static class Student {
...
}
The error already states the problem:
No enclosing instance of type ClassStudy is accessible. Must qualify
the allocation with an enclosing instance of type ClassStudy (e.g.
x.new A() where x is an instance of ClassStudy).
You cannot create instances of inner classes without having an instance of their surrounding class, except when they're static.
So what you need to change your main method to:
// Main Method
public static void main(String[] args) {
ClassStudy classStudy = new ClassStudy();
Student student = classStudy.new Student();
Teacher teacher = classStudy.new Teacher();
}
The reason you're not getting that same error on the line where you initialize Teacher, is because the compiler stops compiling at the first error it finds.
Reimeus has a correct solution. To understand what the message was telling you, you should read up on what static and non-static inner classes are. These should get you started.
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Java inner class and static nested class

Categories