i was reading a book and it has an example which has 2 main methods in its file in different classes , one main method is for testing purposes but i cant understand a way to compile classes individually if there is any way please suggest me
here's the code
/**
* #author achintya
*/
public class StaticTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("tom",4000);
staff[1] = new Employee("dick",60000);
staff[2] = new Employee("harry",65000);
for(Employee e : staff)
{
e.setId();
System.out.println("name" + e.getName() + ",id=" + e.getId() + ",salary=" + e.getSalary());
}
int n = Employee.getNextId();
System.out.println("next available id=" + n);
}
}
class Employee
{
private static int nextId = 1;
private String name;
private double salary;
private int id;
public Employee(String n,double s)
{
name = n;
Salary = s;
id = 0;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
public void setId()
{
id = nextId;
nextId++;
}
public static int getNextId()
{
return nextId;
}
public static void main(String[] args){
Employee e = new Employee("harry",50000);
System.out.println(e.getName() + " " + e.getSalary());
}
}
In your example, you have two classes in the same single source code file.
That is perfectly fair, as only public classes need to go into their own files. This means that you can have N non-public classes in the same source code file.
When things get compiled, there is no more notion of "coming out of the same .java file" though.
You end up with StaticTest.class and Employee.class. And the JVM simply allows you to also invoke a main() method on a non-public class.
But: there is simply no compiling the individual classes. The java compiler works on "file granularity". It will always compile the whole file you give to it, and there is no way for you to say: compile that file, but only the non-public class within.
The short answer: you can't compile individual classes.
The long answer:
You can still run the classes individually.
When you compile the file, you won't see any changes. However, java will compile 2 different classes, StaticTest in the StaticTest.class file, and Employee in the Employee.class file.
Then, to run Employee.class, just run java Employee, and the main method of Employee will run. Read https://stackoverflow.com/a/27313798/13084867 for more
Here are the cmd commands. They can easily be replicated in a Linux environment:
C:\...\Folder> javac StaticTest.java
C:\...\Folder> java StaticTest
Related
I believe the Java way is to keep external classes in separate files. So I've ended up with a directory structure like the following
/main/main.java
/main/libs/class01.java
/main/libs/class02.java
/main/libs/class03.java
Which would be fine but some of the classes are really puny little things, for example if all the classes were just
package libs;
import java.util.*;
public class class01 {
public Integer idno;
public String name;
public class01() {}
idno = 1;
name = "First";
}
}
Then separate files seem like they could get a bit excessive. I'm wondering if there is a way to combine them into a single file similar to the way that you can do in .Net C# with namespaces like the following
using System;
using System.Data;
namespace allClasses {
public class class01 {
public Integer idno;
public String name;
public class01() {}
idno = 1;
name = "First";
}
}
public class class02 {
public Integer idno;
public String name;
public class02() {}
idno = 2;
name = "Second";
}
}
public class class03 {
public Integer idno;
public String name;
public class03() {}
idno = 2;
name = "Third";
}
}
}
Which I can use in my main as if they were all separate
using System;
using allClasses;
namespace main_module {
class main {
static void Main(string[] args) {
class01 newClass01 = new class01();
class02 newClass02 = new class02();
class03 newClass03 = new class03();
}
}
}
I'm sorry for comparing the two it's just that .Net C# is the best example I can show of what I am trying to achieve. I don't know a way of doing this yet in Java, some guidance would be very much appreciated
You can declare them as public static class within another public class.
E.g.
public class Util {
public static class A {}
public static class B {}
}
Then in your main class you can reference them as:
new Util.A();
This will help you combine source code into a single class, but as #oleg-cherednik mentioned, when compiled there will be several separate class files.
Create and implement a class Person. A Person has a firstName and friends. Store the names of the friends as a String, separated by spaces. Provide a constructor that constructs a Person with a given name (passed through arguments) and no friends. Provide the following methods:
public void befriend(Person p)
public void unfriend(Person p)
public String getFriendNames()
public int getFriendCount()
*Hint - you can use p.name to access the name of the Person passed to a method as an argument.
Include a Tester class to make sure your Person has some friends.
How do I store the names of the friends as a String, separated by spaces. (I have to be able to input the names from the main method). I also have no idea how to get rid of already inputted name using the method "unfriend"
public class Person
{
private String firstName;
private String friendNames;
private int friendCount;
public Person(String name)
{
firstName = name;
friendCount = 0;
}
public String getFriendNames()
{
return friendNames;
}
public double getFriendCount()
{
return friendCount;
}
public void befriend(String name)
{
friendNames = friendNames + " " + name;
friendCount++;
}
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
}
Main Method:
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Alex");
p.befriend("John");
p.befriend("Alice");
p.befriend("Mike");
p.befriend("Annette");
p.unfriend("Alice");
System.out.println(p.getFriendCount());
System.out.println(p.getFriendNames());
}
}
Expected output:
2
John Mike
The problems you are having with the methods using the parameter(Person p) are because you have two different variables: friendName (which exists) and name (which does not). Changing the variable friendName to name will take care of some of the errors you are receiving.
(Also the method getFriendCount() returns friendsCount, but should return friendCount (you have an extra s in there) and your assignment calls for a method called befriend, not bestFriend.)
How to delete friends:
You can delete a friend by parsing the friend out of the friendNames string and then concatenating the two resulting strings back together:
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
I would suggest changing befriend and unfriends parameters to accept a String instead of a Person object. Person already has access to its own object and in your main you are trying to pass them Strings anyways. Here is what befriend should look like:
public void befriend(String name) //Changed to "befriend"
{
friendNames = friendNames + " " + name;
friendCount++;
}
Also, you only need one constructor for Person, which should look like this:
public Person(String name)
{
firstName = name;
friendCount = 0;
}
When I run your program (using these changes) I get the following output:
2.0
John Mike
When i try to compile an aggregation program , i receive an error saying "class,interface,enum expected". Here is my code. please help me solve this issue.
class employee
{
private String name;
private String address;
private float salary;
public employee(String na, String add,float sal)
{
name = na;
address = add;
salary = sal;
}
public void showEmpDetails()
{
System.out.println("Name " + name);
System.out.println("Address " + address);
System.out.println("Salary " + salary );
System.out.println();
}
}
import java.util.vector;
class company
{
private String comname;
private vector vt;
public company(String na)
{
comname = na;
vt = new vector();
}
public void addEmployee(employee e)
{
vt.addElement(e);
}
public void showComDetails()
{
System.out.println("Company Name " + comname);
int x = vt.size();
int y = 0;
while(y<x)
{
object e = vt.elementAt(y);
e.showEmpDetails();
y++;
}
}
}
public class demo
{
public static void main(String[] args)
{
employee e1 = new employee("Ashan","Kandy",2000.0f);
employee e2 = new employee("Steve","California",2500.0f);
employee e3 = new employee("Elon","South Africa",2500.0f);
company c1 = new company("Apple");
c1.addEmployee(e1);
c1.addEmployee(e2);
c1.addEmployee(e3);
c1.showComDetails();
}
}
Note:- i receive only one error. and also can anybody tell me why can't i have more than one public class in java.
Well, your code has more than one error actually. The reason for your specific error is that import should be at beginning of the file, not in the middle.
And my understanding of why only one public class is allowed for each file is:
It makes things clearer.
By reading the class name and document to this class, you could quickly know what the whole file is used for. If we allow multiple public classes in one file, like C++, then we have to jump inside of the file to understand it.
Notice Java is a strong object-oriented language, i.e. everything in Java is Object. So when importing, you are importing a file. It would be more complicated if one file contains multiple public classes.
It simplify testing.
Each public class could have a main function. And you could run any main function of a file Demo.java simply by java Demo. This is really nice, so that you could write test code, or example of usage in main function to show other contributor how this class should be used.
There have to be other more in-depth reason for single public class in Java. But these are my perspective.
Here is my code
class Bomb {
static String description = "bomb description";
static int id = 1;
private String name;
private int size;
public static void Bomb() {
id++;
System.out.println(" " + description + " " + id);
}
public void setName(String name) {
this.name = name;
}
public void setSize(int size) {
this.size = size;
}
public void printout() {
System.out.println(" " + name + size);
}
}
public class array {
public static void main(String args[]) {
Bomb.Bomb();
Bomb detenator = new Bomb();
Bomb destroyer = new Bomb();
destroyer.setName("hr4");
destroyer.setSize(43);
detenator.setName("m1s");
detenator.setSize(34);
detenator.printout();
destroyer.printout();
}
}
I want the description to print with each bomb object. but the description prints by itself.
any one got any idea how to fix that?
also please suggest any alternative ways I could've written this code, but don't make it to complicated. i just started learning java so i probably wont understand complex stuff.
I short, there are no "static constructors".
You may want something that references a static member, like this:
public Bomb() {
id++;
System.out.println(" " + Bomb.description + " " + id);
}
Please go over the Java tutorial of constructors:
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
Your definition of constructor is completely messed up.
As #Reut Sharabani mentioned there is no something like static constructor. You are using constructors to initiate object of a class. And static let you use method just by calling ClassName.staticMethod() without creating object of the class (one ruling out another). If static constructor would exist you would be able to write something like, for example, ClassName.ClassName() which make no sense.
Constructors are not returning any value, so declaring them as void is an error. Again constructor is used to initialize your object with some values (but unnecessary)
Could any one show me how do I run the main method on this code, please?
I would like to check if there is any compile time error or run-time error, but I got this error message "Could not find or load main class Application".
class Book {
private static int internalID = 0;
private String isbn;
private int myID;
public Book(String isbnP) {
if (isbnP == null) {
throw new IllegalArgumentException("null ISBN not accepted");
}
isbn = isbnP;
myID = internalID++;
}
public String getBookinfo() {
return isbn;
}
public String toString() {
return "<" + myID + "," + isbn + ">";
}
// To Do: Override Object.equals()
// Two objects are equal iff isbn of the two books are same
}
class ComSBook extends Book {
private String category;
public ComSBook(String isbnP, String catP) {
super(isbnP);
category = catP;
}
#override
public String getBookInfo() {
return "ComS " + category + " " + super.getBookinfo();
}
}
class NetworkBook extends ComSBook {
private boolean isWithCD;
public NetworkBook (String isbnP, boolean withCD){
super(isbnP,"Network");
isWithCD = withCD;
}
#override
public String getBookInfo(){
return super.getBookInfo() + " withCD: " + isWithCD;
}
}
class ReviewPolymorp{
public static void main(String[] args){
Book abook = new Book("A-1");
Book bbook = new Book("B-1");
ComSBook csbook = new ComSBook("C-11", "General");
NetworkBook netbook = new NetworkBook("N-11", true);
System.out.println(abook);
System.out.println(bbook);
System.out.println(csbook);
System.out.println(netbook);
abook = csbook;
System.out.println(abook.getBookinfo());
bbook = netbook;
System.out.println(bbook.getBookinfo());
netbook = (NetworkBook) bbook;
System.out.println(netbook.getBookinfo());
netbook = (NetworkBook) csbook;
System.out.println(netbook.getBookinfo());
netbook = csbook;
}
}
You're file should be ReviewPolymorp.java and class ReviewPolymorp{ should be public, since it the lauching point of the program with the main method
You may also want to check that the Main class in the project is ReviewPolymorp. I only know how to do this in Netbeans
Right-click on the Project
Select Properties
Click Run
Make sure your ReviewPolymorpi the Main Class with fully qualified name e.g. mypackage.ReviewPolymorp
Then rebuild your project
When I copy your code to my IDE(It's eclipse),a compile error show up on this line:
netbook = csbook;
You can't cast an instance of super class to subclass.
After disable this line,I get output from console once run the code:
<0,A-1>
<1,B-1>
Exception in thread "main" <2,C-11>
<3,N-11>
C-11
N-11
N-11
java.lang.ClassCastException: com.test.ComSBook cannot be cast to com.test.NetworkBook
at com.test.ReviewPolymorp.main(ReviewPolymorp.java:75)
It's the same problem with the compile error above.
After disable these three lines
netbook = (NetworkBook) csbook;
System.out.println(netbook.getBookinfo());
csbook = netbook;
Code is work well without any modification.