Skip to content
Advertisement

How to create a new object of Public Class

I am a newbie in Java, although I have knowledge of Object Oriented Programming from Python but I’m currently having problem understanding this example on creating public class either combining the classes together or in different files and then compile them

public class Vehicle {
  int maxSpeed;
  int wheels;
  String color;
  double fuelCapacity;  

  void horn() {
    System.out.println("Beep!");
  }  
}
class MyClass {
  public static void main(String[ ] args) {
    Vehicle v1 = new Vehicle();
    Vehicle v2 = new Vehicle();
    v1.color = "red";
    v2.horn();
  }
}

The example above was given at Sololearn where I am currently learning, but it only works in Sololearn java compilers. Other compiles throw error

Unable to find static main(String[]) in vehicle

Or main method not found

Advertisement

Answer

First of separate these two classes in different files or make Vehicle class nested in MyClass Nested code will look like this —

class MyClass {

public class Vehicle {
  int maxSpeed;
  int wheels;
  String color;
  double fuelCapacity;  

  void horn() {
    System.out.println("Beep!");
  }  
}

  public static void main(String[ ] args) {
    Vehicle v1 = new Vehicle();
    Vehicle v2 = new Vehicle();
    v1.color = "red";
    v2.horn();
  }
}

Save this file code as MyClass.java. If you want to run this code you can either use some java editor like eclipse or Netbeans or you can run this via cmd but you should have JDK installed in your system. To know more about it you can ping me any time. Let me know if you are successfully able to run this code. will be happy to help you 🙂

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement