i am new to java is there is any possible way of calling a function within same class without creating a object for the class my program is
public class Puppy{
public Pup(String name){
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
public Pup( "tommy" );
}
}
i want to call function pup without creating object for it ,is it possible?
You can declare the method to be static:
public static void Pup(String name){
...
}
As an aside: you should use standard Java naming conventions and start your method name with a lower-case letter:
public static void pup(String name){ ...
Try this:
public class Puppy{
public static void Pup(String name){
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
Pup("tommy");
}
}
You can define Pup as statis method like:
public static void Pup(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
And from main call it like:
Pup("tommy");
There are couple of issues in your code:
You don't have valid return type for your method Pup. If you dont return anything you should add void as return type.
You can't use public or any access modifier within any method. So you need remove public from method call.
I'm not sure but maybe....
Inside your main method, you can simply use this statement,
Pup("Your Name");
Your Pup method should have a valid return statement and use these modifiers,
public static
if it's a returning method
public static void
if it's a void method
Related
public class StaticFinalExample {
static String str;
public void StaticFinalExample() {
System.out.println("In Constr");
str = "H";
}
public static void main(String[] args) {
StaticFinalExample t = new StaticFinalExample();
System.out.println(str);
}
}
In above example the output is null.
Why was not the constructor called?
Constructors don't have a return type. There shouldn't be void in your StaticFinalExample() method, if that's your constructor.
Avoid using class name as a method name, it's ambiguous. When we notice any name having same value as class, our mind reads as a class name not as actual usage (method name in your case).
It's not a good practice. It does not mean you can not use method name as class name, but you should avoid using same name.
I am trying to learn how constructors work and I have been trying to debug this simple java program but I cannot get it to run. Eclipse simple refuses to acknowledge its presence and just runs an earlier project. Any ideas would be very gratefully received - I am struggling to see what I have done wrong.
package timber;
public class Person {
private String firstName;
private String lastName;
private String address;
private String username;
public Person(String personFirstName, String personLastName, String personAddress, String personUsername)
{
firstName = personFirstName;
lastName = personLastName;
address = personAddress;
username = personUsername;
}
public void displayPersonDetails()
{
System.out.println("Name: " + firstName + " " + lastName);
System.out.println("Address: " + address);
System.out.println("Username: " + username);
}
}
I then have a second class that contains the main method
package timber;
public class PersonExample {
public void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
dave.displayPersonDetails();
}
}
could you please add static in main method :-
public static void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
dave.displayPersonDetails();
}
Your main method always needs to be static.
See Why is the Java main method static?
Replace,
public void main(String[] args)
with
public static void main(String[] args)
Your main method needs to be 'static'. Why? If you want to call a method in Java, there are two ways
Create an instance of class and use that object to call it's methods
Make a method 'static' so that you can call the method using the class name and no instance creation needed.
The 'main' method, if non-static (like in your case) you have to create an instance of it's class to call. But, where would you create an instance of that class, where your main method is residing? Create another class and call from there? and create yet another class to call this class? It will never end. I mean there has to be a starting point right?
By giving the method the name 'main' and by adding the keyword 'static' in it's signature, you help JVM call that method without the need to an create instance.
Just change
public void main(String[] args)
to
public static void main(String[] args)
Everything is fine you have just missed the static keyword .
Instead of
public void main(String [] args)
Use
public static void main(String[] args)
public class MainForm {
String varpass = "This is a string that has to be passed.";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void place1 (){
//=======================================Method calls from another class========================================
//Calls from another class. It is non-static and thus requires it to be instantiated. EG. class var = new class();
Methods call = new Methods();
System.out.println(call.t1());
//Calls from another class. It is non-static void and thus requires it to be instantiated and be called straight.
call.t3();
//Calls from another class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(Methods.t2());
//Calls from another class. It is static void and thus does not require it to be instantiated.
Methods.t4();
//Trying to call a variable that was sent.
Methods.getvar(varpass);
call.getvar(varpass);
//=======================================Method calls from current class========================================
MainForm mcall = new MainForm();
//Calls from within the same class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(mcall.t1());
mcall.t3();
System.out.println(t2());
t4();
}
public static void main(String[] args) {
MainForm place = new MainForm();
place.place1();
}
}
public class Methods {
String var1 = "This is a public String variable";
String getVar = "Initial";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void getvar(String varsent){
String msg = "getver() Variables are varsent("+varsent+"), getVar("+getVar+"), getVar(";
getVar = varsent;
msg = msg + getVar+")";
System.out.println(msg);
}
}
Here is the errors below
Methods.getvar(varpass);
call.getvar(varpass);
top one is giving non-static cannot be referenced from a static context
bottom one is saying cannot resolve method 'println(void)'
You can tell im using this as practice to call methods.
Here im trying to pass a variable varpass that contains a string. I want it pass that variable to getvar in Methods. in that getvar it takes a variable in Methods displays it before altering it then again after alter.
Im trying to understand how this works. Any insight would be appreciated.
This line
Methods.getvar(varpass);
is a static call. You try to call the static Method getvar from your Methods class. This method however is not static and therefor requires an instance of Method.
This line
call.getvar(varpass);
works fine. It in fact is the solution to the first line, where you reffere a non-static method from a static context
You cannot refer to a non-static variable/field from a static method, because a non-static field may vary between instances of a class. To solve it, make varpass static:
static String varpass = "This is a string that has to be passed.";
The second error results from the definition of getvar:
public void getvar(String varsent);
Since it does not return anything, it cannot be used in a System.out.println() as there is no definition of println accepting void (It doesn't know what to print).
Also, Methods.getvar(varpass) should be Methods.getvar(MainForm.varpass), because there is no local variable with that name.
Can call a method by class name in same package without create object of class or without inheritance in java
public class BoxWeight /*extends Box*/{
public static void main(String[] args) {
/*BoxWeight myCat = new BoxWeight();*/
/*Box myAnimal = myCat;*/
Box.testClassMethod();<------------ why this possible
/* myAnimal.testInstanceMethod();*/
}
}
public class Box /*extends Bicycle*/{
public static void testClassMethod() {
System.out.println("The class" + " method in Box.");
}
public void testInstanceMethod() {
System.out.println("The instance " + " method in Box.");
}
}
my question is not this as you seems my qestion is this "Can call a method by class name in same package without create object of class or without inheritance in java" but i have fix this i want to confirm is this possible or not
You can call a method with the syntax ClassName.methodName() if the method is declared static, eg
class ClassName {
static void methodName() {
//...//
}
}
More info about static class members can be found in the Java Tutorials.
Make your method static then you can call that method by class name.
class A {
static void display(){
System.out.println("Called..");
}
}
In same package you can call it as .
A.display();
I have a simple problem that I've been stuck on for some time and I can't quite find the answer to. Basically, I'm creating an object and trying to access the variables without using static variables as I was told that is the wrong way to do it. Here is some example code of the problem. I receive an error in the first class that can not be resolved to a variable. What I would like to be able to do is access t.name in other methods outside of the main, but also in other classes as well. To get around this previously I would use Test2.name and make the variable static in the Test2 class, and correct me if I'm wrong but I believe that's the wrong way to do it. Any help would be greatly appreciated =)
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
public class Test2 {
String name;
public Test2 (String nm) {
name = nm;
}
}
I see others have posted code snippets, but they haven't actually posted why any of this works (at the time of this writing.)
The reason you are getting a compilation error, is that in your method
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
Variable t's scope is just that method. You are defining Test2 t to only be in the main(String[] args) method, so you can only use the variable t in that method. However, if you were to make the variable a field, like so, and create a new instance of the Test class,
public class Test {
Test2 t;
public static void main(String[] args) {
Test test = new Test();
test.t = new Test2("Joe");
test.displayName();
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Then you should no longer be getting any compilation errors, since you are declaring the variable t to be in the class Test scope.
You may give the reference to your test object as an argument to method displayName:
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println("Name2: " + test.name);
}
}
Note: I also made displayName a static method. From within your main method you can only access static methods without reference.
Modify the Test class to this
public class Test {
private static Test2 t;
public static void main(String[] args) {
t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Use a getter for your purpose. This is a side solution to your problem, but generally this is how you should retrieve instance variables, using getters.
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println(test.getName());
}
}
public class Test2
{
private String name;
public Test2 (String nm)
{
name = nm;
}
public String getName()
{
return name;
}
}
Always remember, variables in your class should be private. That protects it from access from outside the class. Hence, getters are the only way to access them. And setters or constructors to initialize them.
Fewer statics the better I reckon.
I would Instantiate Test and call displayName on the instance of it, then pass the instance of Test2 to displayName.
But it does depend on what the overall aim is