Why does this java code doesn't work on my pc?

for example:
package one;
public class Alpha {
//member variables
private int privateVariable = 1;
int packageVariable = 2; //default access
protected int protectedVariable = 3;
public int publicVariable = 4;
//methods
private void privateMethod() {
System.out.format("privateMethod called%n");
void packageMethod() { //default access
System.out.format("packageMethod called%n");
protected void protectedMethod() {
System.out.format("protectedMethod called%n");
public void publicMethod() {
System.out.format("publicMethod called%n");
public static void main(String[] args) {
Alpha a = new Alpha();
a.privateMethod(); //legal
a.packageMethod(); //legal
a.protectedMethod(); //legal
a.publicMethod(); //legal
System.out.format("privateVariable: %2d%n",
a.privateVariable); //legal
System.out.format("packageVariable: %2d%n",
a.packageVariable); //legal
System.out.format("protectedVariable: %2d%n",
a.protectedVariable); //legal
System.out.format("publicVariable: %2d%n",
a.publicVariable); //legal
As you can see, Alpha can refer to all its member variables and all its methods, as shown by the Class column in the preceding table. The output from this program is:
privateMethod called
packageMethod called
protectedMethod called
publicMethod called
privateVariable: 1
packageVariable: 2
protectVariable: 3
publicVariable: 4
when above example runs on my pc:
it works below description:
D:\javacode>javac Alpha.java
D:\javacode>java Alpha
Exception in thread "main" java.lang.NoClassDefFoundError: Alpha (wrong name: on
e/Alpha)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
why it runs wrongly and who can help me?
thanks

if i runs it below:
D:\javacode>javac one\Alpha.java
D:\javacode>java one.Alpha
privateMethod called
protectedMethod called
protectedMethod called
privateVariable: 1
packageVariable: 2
protectedVariable: 3
publicVariable: 4
it runs well!

Similar Messages

  • Text messages and imessages marked as delivered yet not received since last update. I cannot make sense of the troubleshooting page, why does this complex machine not just work?.

    I updated my iphone -again, and now my girlfriend (and who knows who else) is not reliably receiving messages. I try sending as iMessage and as SMS and have iMessage checked in my options and send as text message if iMessage doesn't work also checked. It was working fine, I updated, now it's patchy at best and although messages are marked as delivered they aren't and I don't know unless I phone the recipient up. Have tried restarting, resetting and digging through the trouble shooting pages... Apple products used to just work, now my phone is like a puzzle that I have to solve. I'm ditching apple in October when my contract is up but would like to send texts in the meantime, any ideas?

    Awesomez. Thanks apple support community, very helpful indeed. About as helpful as a phone that stops sending texts after the manufacturers update it. No worries though, I got a HTC yesterday, put my sim in and guess what? It works. Close this thread down thanks mods.

  • After updating to iOS 8.0.2 in my iPhone 5S, why does automatic landscape orientation doesn't work?

    I recently updated to iOS 8.0.2 in my iPhone 5S. Since that update, landscape orientation doesn't work for any application. I have ensured that the Portrait Orientation lock is Off.

    I have a workaround, if you lock then unlock the orientation lock it seems to work again.

  • HT3775 why does this error code: 2.2012.DVDRiP.XviD.AC3-BHRG.avi, pop up when i try to view my movie download

    I am trying to view a movie i've downloaded via utorrent and when i try to open it this error code pops up:2.2012.DVDRiP.XviD.AC3-BHRG.avi
    Please help..

    I seem to have fixed it by putting <div  class="clearfloat"></div> after the navigation bar?

  • Why this simple code doesn't work?????

    i get error "java.sql.SQLException: Operation not allowed after ResultSet closed "
    try{
                Class.forName("com.mysql.jdbc.Driver");
                Connection dbcon = DriverManager.getConnection("jdbc:mysql://localhost:3306/db?user=user&password=pasw&useUnicode=true&characterEncoding=utf-8");
                String query = "SELECT * FROM  data where parent_id='xxsds^1'";
                Statement statement = dbcon.createStatement();
                ResultSet rs = statement.executeQuery(query);
                while(rs.next())
                    String name = rs.getString("name");
                    String query2 = "SELECT * FROM  data where parent_id='"+name+"'";
                    statement.execute(query2);
                    ResultSet rs2 = statement.getResultSet();
                    while(rs2.next())
                        String name1 = rs2.getString("name");
            catch(Exception ex){out.println(ex);}thanks a lot

    You need to use two separate statments if you're going to interleave the queries like that. I'd think you could get by with a single query and a join though, but I didn't actually look at what your queries are doing.
    Also, you should use PreparedStatement, a "?" parameter, and PS's setString method, rather than a plain old Statement where you have to maually handle string quoting.

  • Why does this abstract class and method work without implement it?

    hi,
    I have seen many times that in some examples that there are objects made from abstract classes directly. However, in all books, manual and tutorials that I've read explain that we MUST implement those methods in a subclass.
    An example of what I'm saying is the example code here . In a few words that example makes Channels (java.nio.channel) and does operations with them. My problem is in the class to make this channels, because they used the ServerSockeChannel class and socket() method directly despite they are abstracts.
       // Create a new channel: if port == 0, FileChannel on /dev/tty, else
       // a SocketChannel from the first accept on the given port number
    private static ByteChannel newChannel (int netPort)
          throws Exception
          if (netPort == 0) {
             FileInputStream fis = new FileInputStream ("/dev/tty");
             return (fis.getChannel());
          } else {
    //CONFLICT LINES
             ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
             ssc.socket().bind (new InetSocketAddress (netPort)); //<--but here, this method (socket) is abstract. WHY RETURN A SOCKET????????  this mehod should be empty by default.
             System.out.print ("Waiting for connection on port "
                + netPort + "...");
             System.out.flush();
             ByteChannel channel = ssc.accept();
             ssc.close();
             System.out.println ("Got it");
             return (channel);
       } I test this code and works fine. So why can it be??
    Also, I read that the abstract classes can't have static methods. Is it true???
    Please Help!!
    PS: i have seen this kind of code many times. So i feel that I don't understand how its really the abstract methods are made.
    PS2: I understand that obviously you don't do something like this: *"obj = new AbstractClass(); "*. I dont understand how it could be: ServerSocketChannel ssc = ServerSocketChannel.open(); and the compiler didn't warn.

    molavec wrote:
    ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
    The static method creates an instance of a class which extends ServerSocketChannel, but is actually another non-abstract class.I thought that, but reading the documentation I saw that about open() method:
    Opens a server-socket channel.
    The new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.
    The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.
    ...and the problem is the same openServerSocketChannel is abstract, so i don't understand how it could return a ServerSocketChannel.There is a concrete implementation class that has implemented that method.
    I guess that really the open() method use a SelectorProvider's subclase but it doesn't appear in the doc.It doesn't need to. First, you don't care about those implementation details, and second, you know that if the class is abstract, it must use some concrete subclass.
    Ok, I speak Spanish by default (<-- this sounds like "I am a machine", ^_^' ). So, I didn't know how to say that the method would be {}. Is there a way to say that?? I recommendable for me to know, for the future questions o answers.Not sure what you're saying here. But the other respondent was trying to explain to you the difference between an abstract method and an empty method.
    // abstract method
    public abstract void foo();
    // empty method
    public void bar() {
    Which class does extend ServerSocketChannel? I can not see it.It may be a package-private class or a private nested class. There's no need to document that specific implementation, since you never need to use it directly.

  • My java code doesn't work the way it should

    Hello can someone tell me why this code isn't printing on my linux computer?
    I found something about a bug in java for printing with linux see link.
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6181488
    I hope someone can help me.
    import javax.print.*;
    import javax.print.attribute.*;
    import java.io.*;
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.CubicCurve2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.SimpleDoc;
    import javax.print.attribute.DocAttributeSet;
    import javax.print.attribute.HashDocAttributeSet;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class PrintingOneTwoFour {
       static class MyComponent extends JPanel implements Printable {
         public void paint(Graphics g) {
           Graphics2D g2d = (Graphics2D) g;
           g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
               RenderingHints.VALUE_ANTIALIAS_ON);
           g2d.setPaint(Color.BLUE);
           g2d.setStroke(new BasicStroke(3));
           CubicCurve2D cubic = new CubicCurve2D.Float(10, 80, 60, 30, 110, 130, 160, 80);
           g2d.draw(cubic);
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
           if (pageIndex == 0) {
             paint(g);
             return Printable.PAGE_EXISTS;
           } else {
             return Printable.NO_SUCH_PAGE;
       public static void main(String args[]) throws Exception {
         final JFrame frame = new JFrame();
         Container contentPane = frame.getContentPane();
         final Component printIt = new MyComponent();
         contentPane.add(printIt, BorderLayout.CENTER);
         JButton button = new JButton("Print");
         contentPane.add(button, BorderLayout.SOUTH);
         ActionListener listener = new ActionListener() {
           public void actionPerformed(ActionEvent e) {
             DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
          //      PrintService printService = PrintServiceLookup
             //     .lookupDefaultPrintService();
          PrintService[] services  = null;
             PrintService   myPrinter = null;
          //   DocFlavor myFlavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
             PrintRequestAttributeSet jobAttrs = new HashPrintRequestAttributeSet();
             services = PrintServiceLookup.lookupPrintServices( flavor, jobAttrs );
    if ( System.getProperty( "os.name" ).startsWith( "Windows" ) )
        myPrinter = PrintServiceLookup.lookupDefaultPrintService();
      else {
        try { 
            Process child = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "echo ${PRINTER:-$LPDEST}" });
            BufferedReader rdr = new BufferedReader(new InputStreamReader( child.getInputStream() ));
            String envPrinter = rdr.readLine().trim();
            System.out.println("Printer "+envPrinter+rdr.readLine());
         child.destroy();
            for ( int i=0; myPrinter == null && i<services.length; i++ )
                if ( services.getName().equals( envPrinter ) )
    myPrinter = services[i];
              System.out.println("myPrinter "+myPrinter);
    catch ( Exception ignore )
    System.out.println("Exception "+ignore);
    if(myPrinter==null)     
    myPrinter = services[0];
    System.out.println("myPrinter == null "+myPrinter);
         DocPrintJob job = myPrinter.createPrintJob();
    DocAttributeSet das = new HashDocAttributeSet();
    Doc doc = new SimpleDoc(printIt, flavor, das);
    try {
    job.print(doc, jobAttrs);
    } catch (PrintException pe) {
    pe.printStackTrace();
    button.addActionListener(listener);
    frame.setSize(350, 350);
    frame.show();

    Nobody????????????

  • TS4268 My iMessage doesn't work on my iPad. My software is up to date, wifi is working, apple ID is working but the verification stops and goes back to sign on. Why does this happen?

    My iMessage doesn't work on my iPad. My software is up to date, wifi is working, apple ID is working but the verification stops and goes back to sign on. Why does this happen?

    Look at no. 5 in this text which was copied from Apple's support site for troubleshooting Messages and FaceTime activation.
    Troubleshooting Apple ID activation
    After each step, toggle iMessage and FaceTime off and then on again in Settings > Messages and Settings > FaceTime.
    Update to the latest version of iOS.
    Ensure that you have an active Internet connection. You can complete activation using Wi-Fi or a cellular data connection. Check your Wi-Fi network using standard Wi-Fi network troubleshooting.
    If you receive an error when signing in to your Apple ID, visit myinfo.apple.com, sign in to your account, and ensure that the primary email address has been verified.
    Ensure that FaceTime has not been restricted: Settings > General > Restrictions > FaceTime.
    In Settings > General > Date & Time, ensure that Set Automatically is on. If Set Automatically is on, but the incorrect time zone is displayed, turn Set Automatically off and then choose the correct time zone, date, and time. Then turn Set Automatically on again.
    Enable iMessage and FaceTime while connected to another Wi-Fi network in a different location.
    This is the support kb article.
    http://support.apple.com/kb/ts4268

  • How to use documentbeforesaved method? And why my code doesn't work in template files?

    Can someone help me with these two codes?
    ----Beginning of code 1-------------
    Private WithEvents App As Word.Application
    Private Sub Document_Open()
    Set App = Word.Application
    End Sub
    Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
    MsgBox("BeforeSave")
    End Sub
    --------------End of the code----------------
    Beginning of code 2--------------- Code 2 is from https://msdn.microsoft.com/en-us/library/office/ff838299(v=office.15).aspx
    Public WithEvents appWord as Word.Application 
    Private Sub appWord_DocumentBeforeSave _ 
     (ByVal Doc As Document, _ 
     SaveAsUI As Boolean, _ 
     Cancel As Boolean) 
     Dim intResponse As Integer 
    Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
    MsgBox("BeforeSave")
    End Sub
    In the first code, they have:
    Private Sub Document_Open()
    Set App = Word.Application
    End Sub
     I test these two codes in "This document" object, and I find out the first code works but the second code are not!
    Why second code doesn't work?
    Extra question: I am using microsoft 2013. I insert this code into a macro-enabled template. But when I am about to save my file I am expecting these code works. However, they didn't work!
    Thank you for solving these problem for me!

    Hello,
    Please note that the code snippet 2 in your post is different from the code snippet in the MSDN document. Also please read the comments of the MSDN code sample:
    This example prompts the user for a   yes or no response before saving any document.
    This code must be placed in a   class module, and an instance of the class must be correctly initialized to   see this example work; see
    Using Events with the Application Object for   directions on how to accomplish this.
    Public WithEvents appWord   as Word.Application
    Private Sub   appWord_DocumentBeforeSave _
     (ByVal Doc As Document, _
     SaveAsUI As Boolean, _
     Cancel As Boolean)
     Dim intResponse As Integer
     intResponse = MsgBox("Do you really   want to " _
     & "save the document?", _
     vbYesNo)
     If intResponse = vbNo Then Cancel = True
    End Sub
    So the problem in your code snippet 2 is that you didn't put it into a class module and initialize the class module. If you just put it into ThisDocument, you have to initialize the word application object.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • I cannot send an email from my iPad 2? No problem receiving, why does this happen? Have tried the suggestions for setting up email and after doing the sync mail through iTunes receiving worked great but still cannot send? Any help would be great

    I cannot send an email from my iPad 2? No problem receiving, why does this happen? Have tried the suggestions for setting up email and after doing the sync mail through iTunes receiving worked great but still cannot send? Any help would be great!

    The fact that you can receive means you have a valid e mail address, and have established the connection to the incoming server, so all of that works.  Since the send does not work, that means your outgoing server is rejecting whatever settings you used formthe outgoing set up.  Try them again. 
    Google your particular isp, and ipad and many times you will find the exact settings needed for your isp.  Or tell us here, and soneone else may be on the same isp.  Some mail services need you to change a port, or have a unique name for the outgoing server.  
    Kep trying.

  • HT2499 I have a new MacBook Pro with OS X Lion 10.7.4. The DVD player does not have a feature to store film clips. Why? This is useful for my work and I had it on my older computer? Why the loss of capacity?

    I have a new MacBook Pro with OS X Lion 10.7.4. The DVD player does not have a feature to store film clips. Why? This is useful for my work and I had it on my older computer? Why the loss of capacity?

    I cannot recall the DVD player ever being a place to "store" videos - it is simply an app to play videos.
    If your machine is new, then iMovie should be included as the "shrunk" version of iLife is included with Lion (iMovie, Garageband, and iPhoto). However, iMovie is not a place to store videos either - it is a video editor. You import your clips and edit them in order to then burn to a DVD or share via a social media site.
    Have you considered simply dragging the clips to your folder "Movies"? That would be a great place to just store them (please be aware that videos are usually large files, so keep your hard drive space in mind so you keep a minimum free and available for the OS to operate properly):

  • Why can't I find events with cmd-F? I can see the appointment I am searching for, but the search cmd-F function does not find it. Why is this. It used to work...

    Why can't I find events with cmd-F? I can see the appointment I am searching for, but the search cmd-F function does not find it. Why is this. It used to work...

    Why can't I find events with cmd-F? I can see the appointment I am searching for, but the search cmd-F function does not find it. Why is this. It used to work...

  • The ussd code doesn't work on my iphon since i update to ios 7.0.3 what can i do for this problem?

    the ussd code doesn't work on my iphon since i update to ios 7.0.3 what can i do for this problem?

    Maybe
    SOLUTION: circle with red square Some Music Won't Play After...: Apple Support Communities

  • The monitor of my MacBook Pro suddenly became all black, I tried to reset but it did not work, what should I do? Why does this happen?

    The monitor of my MacBook Pro suddenly became all black, I tried to reset but it did not work, what should I do? Why does this happen?

    I advise to reply to the one you want to reply to.
    You have had good information here. I will not repeat that here.
    I would like to add:
    you have incompatible software: start in SafeMode, read Woodmeister and see if it is free of issues.
    Akamai is crap software needed or not, Huawei the same.
    It is very possible that the keygenerator you used for generating a key for some softwares has infected your mac.
    The non-regular software with the false key(s) are not compatible probably or generate malware. Luckily you can not update them automatically because the keygenerator blocked the software for contacting the developer... I propose to consider getting rid of those softwares by really good uninstalling.
    You have a beautiful mac, don't degenerate it with crapped software. There are alternatives for expensive software, for example Adobe Photoshop has a free alternative (with a less beautiful interface) in GIMP. And so on.
    Lex

  • When ever i turn cellular data off then back on my mobile internet doesent work why does this happen?, when ever i turn cellular data off then back on my mobile internet doesent work why does this happen?

    when ever i turn cellular data off then back on my mobile internet doesent work why does this happen?, when ever i turn cellular data off then back on my mobile internet doesent work why does this happen?

    You only asked the question 4 times.  You have to repeat it at least 10 times to get an answer here, and then only if you supply useful info about your phone.

Maybe you are looking for

  • IPod to TV photos or video not working using S cable

    I just got my iPod AV with the universal dock. I connected them and used the S-Video cable. I connected the cable to my dock and tv, set the iPod to TV out but nothing worked. I must add that I did not connect any power to the iPod or Dock.

  • Add music to a presentation!

    Hello Everyone, I'm running Panther on a iMac G3 333 and AW 6.2.9 and would like to add music to a presentation that I created. I am able to insert the music file into the master file just fine, but the music only plays until it moves to the next sli

  • Major problems with sorting/importing in iphoto.

    Here is the problem I am having. When I try to import some recent pictures I have taken, I get all kinds of errors. First of all if import them through iphoto all of the thumbnails show up but when you double click on them i get a grey box with an ex

  • SD Automatic Batch Determination

    Hi Expert,                   There is some problem in SD automatic batch determination. at the time of PGI message is occur batch of this Suppose i have 100 material in X location and divided in three batch( A,B,C)  A=20 , B=30 , C=50 , Quantity. So

  • HP Pavilion DV7t-2000 Mic and Webcam Error

    I have an HP Dv7t-2000 laptop that is running Windows 7. Recently, my mic and wecam both stop working whenever my screen is raised up. If I tilt my screen down to below 45 degrees (to where the screen is hardly visible) the mic and webcam work fine.