Constructor Inheritance Question

Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
"All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
public class ClassParent
    public static void main(String[] args) {
       ClassParent tester = new ClassParent();
public class ClassChild extends ClassParent
    public static void main(String[] args) {
        ClassChild child = new ClassChild();
}Both classes compiled successfully, which raised the following question:
I understand that the ClassParent default constructor calls the Object's no-argument constructor.
Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
And a somewhat non-related question:
Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
Edit: After running the following code, I realized that the answer to my last question is yes:
public class ClassParent
    public static void main(String[] args) {
       ClassParent tester = new ClassParent();
       boolean test = tester instanceof Object;
       System.out.println(test);
}Edited by: youmefriend722 on May 26, 2008 1:54 PM

youmefriend722 wrote:
I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
Constructor inheritance:
If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
Constructors in general:
In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

Similar Messages

  • Multiple inheritance question

    This just occurred to me. I read the other day that all classes inherit Object. So if I have a class defined as public class A {
    }and I call toString() on an instance of this class, I get Objects toString implementation (assuming it has not been overridden). OK, this I understand.
    Now if instead I havepublic class A extends B {
    }and I call toString() on A, assuming it is not overridden in either A or B, I will still get Objects toString method. My question is, does A still extend Object, or does it inherit the fact that B extends Object? And what happens if I override toString() in B - what will I get if i call toString on an instance of A?

    java.lang.Object is at the root of all class inheritance hierarchies in Java. Therefore, all classes inherit from java.lang.Object, either directly or indirectly.
    When you call a method on an object of class Foo, Foo's inheritance hierarchy is traced starting with Foo and going all the way back to java.lang.Object, looking for an implementation of the method. The first implementation encountered is the one that gets used. So in your example calling toString on an instance of class A will result in B's toString method being executed.
    Hope this makes sense.

  • [Solved] C++ inheritance question

    I have a base class and a bunch of inherited classes.
    I am doing something like this in the main.
    baseclass* base[2];
    base[0]= new _derived1("hello");
    base[1]= new _derived2("world");
    How do I code my base class or what-ever-else so that I CAN'T do this:
    baseclass* base2;
    base2 = new baseclass("class");
    The base class has 1 constructor with an argument type string. I can't have a default constructor.
    So in short. I can create a particular derived class, like a derived1, but can't create a plain base class. (it should throw a compilation error)
    Any help would be appreciated.
    Thanks.
    Last edited by lamdacore (2011-02-06 00:38:43)

    Oh I want a compile error when I do this:
    baseclass* base2;
    base2 = new baseclass("class");
    Example code. So I don't want the base class to be able to make a Base type object. As soon as I do that it SHOULD throw a compilation error.
    class Base{
    public:
    Base(string st):m_st(st)
    virtual ~Base(){
    virtual string ann() const{
    return "";
    virtual string bnn() const{
    return m_st;
    virtual string cnn(string msg) const{
    string k="hey ";
    k.append(msg);
    return k;
    private:
    string m_st;
    class derived1:public Base{
    public:
    derived1(string st):Base(st){
    virtual ~derived1(){
    cout<<"kill";
    virtual string ann() const{
    return "hullo";
    virtual string bnn() const{
    return Base::bnn();
    virtual string cnn(string msg) const{
    string k="hey ";
    k.append(msg);
    return k;
    private:
    string m_st;
    Last edited by lamdacore (2011-02-06 23:38:23)

  • Constructors - Fundamental Questions

    Hello everyone,
    Just a couple of questions from me about the concept of constructors, as I am deeply confused about that matter.
    1)Does the order of the constructors' parameters matter? -
    If for example I have 2 constructors in my class:
    public Beer(String brew, int pints)
    fix the car
    }and
    public Beer(int pints, String brew)
    do the laundry
    }and then I declare in my main app
    beer = new Beer(typeOfBeer, numberOfBeers)Which of the 2 constructors will be used?? OR in other words, what exactly is the program going to do? Laundry or fix the car ?
    2)What is the limit of the number of parameters that can be passed on a constructor?
    3)How can we restrict a method of a class from being accessible(from the same class) if our object is created through a specific constructor?
    Please answer me as simply as possible
    Thank you in advance for your time

    konos5 wrote:
    Hello everyone,
    Just a couple of questions from me about the concept of constructors, as I am deeply confused about that matter.
    1)Does the order of the constructors' parameters matter? -
    If for example I have 2 constructors in my class:
    public Beer(String brew, int pints)
    fix the car
    }and
    public Beer(int pints, String brew)
    do the laundry
    }and then I declare in my main app
    beer = new Beer(typeOfBeer, numberOfBeers)Which of the 2 constructors will be used?? OR in other words, what exactly is the program going to do? Laundry or fix the car ?
    2)What is the limit of the number of parameters that can be passed on a constructor?
    3)How can we restrict a method of a class from being accessible(from the same class) if our object is created through a specific constructor?
    Please answer me as simply as possible
    Thank you in advance for your timeAnswers that I can give
    1. Compiler usually works based on searching for the signatures of a method or constructor, so if you create an object as above where you call new Beer( String, int ) than fix car will pop out.
    2. There are no limits for parameters in a constructor, it is solely your wish on how may you need
    3. This requires you to brush up your knowledge on "Access Modifiers". To make a class member only accessible within a class, do use PRIVATE modifier. Again it depends on what is your whole program is all about
    Regards,
    Thiagu

  • For loops & inheritance question

    I am trying this exercise dealing w/inheritance. I enter at command line a random number of c's, s's and m's. for checking,savings and money market. I then parse the string and check for the character. From there I create one of the accounts. then I am supposed to make a report that displays the past 3 months activities. the first account created gets 500 deposit the from there each account after the first gets an additional 400. so it would be: 500,900,1300,etc. Here is what I have so far, but the report part is where I can't figure out exactly how to go about solving it. Thanks in advance.
    public static void main( String args[] ){
         int intDeposit = 500;
         char charTest;
         Object [] objArray = new Object[args[0].length()];
         for ( int j = 0; j < 3; j ++ ){                        System.out.println( "Month " + ( j +1 ) + ":" );
             for( int i = 0; i < args[ 0 ].length(); i ++ ){
              charTest = args[ 0 ].charAt( i );
                         if (charTest == 'c' ){
                  BankAccount at = new  CheckingAccount( intDeposit );
                  objArray=at;
              else if( charTest == 's' ){
              BankAccount at = new SavingsAccount( intDeposit );
              objArray[i]=at;
              else if( charTest == 'm' ){
              BankAccount at = new MoneyMarket( intDeposit );
              objArray[i]=at;
              else{
              System.out.println( "invalid input" );
              }//else
              intDeposit += 400;
              System.out.println();
         }//for j
         for (int counter = 0; counter < objArray.length; counter ++ ){
              System.out.println( "Account Type: " +
                        objArray[counter].toString() );
              System.out.println( "Initial Balance: " +
                        (BankAccount) objArray[counter].getCurrentBalance() );
         System.out.println( "TotalDeposits: " + objArray[counter].getTotalDeposits() );
         System.out.println();
         }//for i
    }//main
    }//TestBankAccount.java\

    The only thing I think is wrong is the following line:
    System.out.println( "Initial Balance: " +                    (BankAccount) objArray[counter].getCurrentBalance() );
    Should be:
    System.out.println( "Initial Balance: " +                    ((BankAccount) objArray[counter]).getCurrentBalance() );

  • Inheritance questions

    Say a superclass has 3 methods and 3 properties. NExt, I create a subclass which overrides these same 3 methods and properties. Either way, my question really is this... When casting up and down, when it is a subclass and a super class reference, are the properties preserved when it is cast(implicitly) up to a superclass reference, so that, in case it needs to be cast back down (explicitly) to its original subclass form, the subclass properties can still be referred to? Are the original variables still preserved (much like a static variable)?

    are the properties preserved when it is cast(implicitly) up to
    a superclass reference, so that, in case it needs to be cast backAn object instance does not change when it's casted into a superclass reference. This means it can be casted back (if this weren't the case, then all methods that return Object would be pretty useless).
    In addition, accessing an object method via a superclass reference does not mean that you'll invoke a superclass method. Instead, it invokes the method appropriate to the object (otherwise overriding and polymorphism would be pretty useless).
    However, accessing an object's instance variable via a superclass reference does access the superclass variable, not the subclass variable.
    I would suggest playing with this for a while ... here's something to start with:
    public class DROCPDP
        public static void main( String argv[] )
        throws Exception
            Base a = new Base();
            Sub b = new Sub();
            Base c = (Base)b;
            Sub d = (Sub)c;
            System.out.println("\nOperations on A:");
            System.out.println("a.var = " + a.var);
            a.method();
            System.out.println("\nOperations on B:");
            System.out.println("b.var = " + b.var);
            b.method();
            System.out.println("\nOperations on C:");
            System.out.println("c.var = " + c.var);
            c.method();
            System.out.println("\nOperations on D:");
            System.out.println("d.var = " + d.var);
            d.method();       
        private static class Base
            public String var = "Base";
            public void method()
                System.out.println("Called Base.method; variable = " + var);
        private static class Sub extends Base
            public String var = "Sub";
            public void method()
                System.out.println("Called Sub.method; variable = " + var);
    }

  • Constructor inheriting

    Can we inherit a constructor of the base class in the derived class.
    Please help.
    Shravan

    You can always write a constructor of your own, and call the super class constructor:
    public Dummy(int dummy) {  // Constructor for class Dummy which
                                // extends a class with a constructor which takes one int
        super(dummy);
    }/Kaj

  • Small inheritance question

    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.
    Player class and Enemy class contains extra stuff like different image and moves different.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?
    Also,
    If values change in the 'Player' class do the values also change in te 'User' class?
    I am fairly new to java.
    Thanks

    MarcLeslie120 wrote:
    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.Sounds odd. Aren't some players also your enemy? Or is Player me, and everybody else is Enemy?
    Player class and Enemy class contains extra stuff like different image and moves different.Okay. If it's just different, that's one thing. If it's adding extra methods, you probably don't want to inherit.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?If it's going to be a Player, you need to create a Player.
    If values change in the 'Player' class do the values also change in te 'User' class?If you mean an instance variable (a non-static member variable), then there aren't two separate objects. There's just one object, that is both a Player and a User. The variable exists only once.
    Your inheritance hierarchy smells funny, but without more details about what these classes represent and what you're trying to accomplish, it's hard to provide concrete advice.

  • Inheritance question

    I'm working on an assignment but I'm getting the following error when I test the code:
    "Card.java": Error #: 300 : constructor CraftItem() not found in class questiontester.CraftItem at line 3, column 8
    I've already tried a number of things to resolve the issue but it keeps cropping up. Can anyone shed any light on what I'm doing wrong please?
    Here's my code:
    CraftItem.java
    (I know this works because it tested out okay)
    package questiontester;
    public class CraftItem {
    // instance variables
    public String itemCode;
    public double price;
    // constructor
    public CraftItem(String itemCodeValue, double itemPriceValue){
    itemCode = itemCodeValue;
    price = itemPriceValue;
    // getter for itemCode
    public String getItemCode() {
    return itemCode;
    // getter for price
    public double getPrice() {
    return price;
    // setter for itemCode
    public void setItemCode(String itemCodeValue) {
    itemCode = itemCodeValue;
    // setter for price
    public void setPrice(double itemPriceValue) {
    price = itemPriceValue;
    // toString() value
    public String toString() {
    return "Item code is " + itemCode + " and costs " + price + " pounds.";
    Card.java
    (this class extends CraftItem and is where I'm getting the error. The error message highlights the class bit in italics as being the problem)
    package questiontester;
    public class Card extends CraftItem {
    // instance variables
    private String cardType;
    private String cardSize;
    //private String itemCode;
    //private double price;
    // Constructor
    public void Card(String cardTypeValue, String cardSizeValue,
    String itemCodeValue, double itemPriceValue) {
    cardType = cardTypeValue;
    cardSize = cardSizeValue;
    itemCode = super.getItemCode();
    price = super.getPrice();
    // methods
    Test.java
    (this the code I'm using to test functionality - it normally works just fine but the error message cropped up when I tried to extend CraftItem with Card)
    package questiontester;
    public class Test {
    public static void main(String args[]) {
    // creating a new object instance with default values
    // values 123456 and 1.5 could also have been set here
    CraftItem defaultItem = new CraftItem("000000",0.0);
    // calling the toString() method to display the text
    // this should display defaultItem with its initial values
    System.out.println(defaultItem.toString());
    // setting the item code to 123456
    // this overrides the initial String value of defaultItem
    defaultItem.setItemCode("123456");
    // setting the price to 1.5
    // this overrides the initial double value of defaultItem
    defaultItem.setPrice(1.5);
    // calling the toString() method to display the text
    // this should now show defaultItem with its new values
    System.out.println(defaultItem.toString());
    // test to check whether getter methods work
    System.out.println(defaultItem.getItemCode());
    System.out.println(defaultItem.getPrice());
    // test to see that setters work for additional items
    CraftItem anotherItem = new CraftItem("000000",0.0);
    anotherItem.setItemCode("345345");
    anotherItem.setPrice(0.5);
    System.out.println(anotherItem.toString());
    As I say, I'm not sure how to resolve the Error#: 300 so any advice on how to do this would be greatly appreciated.
    Cheers - Nic

    Here's my updated code - I'll repost the Test and CraftItem code too:
    Card.java
    package questiontester;
    public class Card extends CraftItem {
      // instance variables
      private String cardType;
      private String cardSize;
      private String itemCode;
      private double price;
      // Constructor
      public Card(String cardTypeValue, String cardSizeValue) {
            super(itemCodeValue, itemPriceValue);
            cardType = cardTypeValue;
            cardSize = cardSizeValue;
    // methods
    CraftItem.java
    package questiontester;
    public class CraftItem {
      // instance variables
      public String itemCode;
      public double price;
      // constructor
      public CraftItem(String itemCodeValue, double itemPriceValue){
        itemCode = itemCodeValue;
        price = itemPriceValue;
      // getter for itemCode
      public String getItemCode() {
        return itemCode;
      // getter for price
      public double getPrice() {
        return price;
      // setter for itemCode
      public void setItemCode(String itemCodeValue) {
        itemCode = itemCodeValue;
      // setter for price
      public void setPrice(double itemPriceValue) {
        price = itemPriceValue;
      // toString() value
      public String toString() {
        return "Item code is " + itemCode + " and costs " + price + " pounds.";
    Test.java
    package questiontester;
    public class Test {
      public static void main(String args[]) {
        // creating a new object instance with default values
        // values 123456 and 1.5 could also have been set here
        CraftItem defaultItem = new CraftItem("000000",0.0);
        // calling the toString() method to display the text
        // this should display defaultItem with its initial values
        System.out.println(defaultItem.toString());
        // setting the item code to 123456
        // this overrides the initial String value of defaultItem
        defaultItem.setItemCode("123456");
        // setting the price to 1.5
        // this overrides the initial double value of defaultItem
        defaultItem.setPrice(1.5);
        // calling the toString() method to display the text
        // this should now show defaultItem with its new values
        System.out.println(defaultItem.toString());
        // test to check whether getter methods work
        System.out.println(defaultItem.getItemCode());
        System.out.println(defaultItem.getPrice());
        // test to see that setters work for additional items
        CraftItem anotherItem = new CraftItem("000000",0.0);
        anotherItem.setItemCode("345345");
        anotherItem.setPrice(0.5);
        System.out.println(anotherItem.toString());
    Update
    I've removed the void and the original error#: 300 message has gone, replaced by the following two:
    "Card.java": Error #: 300 : variable itemCodeValue not found in class questiontester.Card at line 14, column 15
    "Card.java": Error #: 300 : variable itemPriceValue not found in class questiontester.Card at line 14, column 30

  • Constructor / inheritance / encapsulation issue

    Please consider this code:
    public class Main {
      public static void main(String[] args) {  new BBB();  }
        public static class AAA {
            private int x;
            AAA() {  foo();  x = 123; }
            public void foo() { println("AAA::foo()"); }
        public static class BBB extends AAA {
            BBB() { super(); }
            public void foo() { println("BBB::foo()"); }
    }The result is that the constructor in AAA invokes BBB's foo(), which violates encapsulation. I would just like to ask:
    Invoking public/protected instance methods in the constructors of non-final classes is absolutely forbidden, right?
    I am not asking why that happens. Rather, I just want to confirm the answer is "yes", it is forbidden. Or, if there are cases when it is ok, I am interested in learning them. Doing more that initializing instance variables in a constructor seems intriguing. But doing so could create weird situations (as in AAA's constructor) where you can access the private variable "x" of AAA and then invoke the BBB's foo().
    ps: the "users online" and "guests online" forum statistics always equal zero.

    dpxqb wrote:
    abillconsl wrote:
    dpxqb wrote:
    Please consider this code:
    The result is that the constructor in AAA invokes BBB's foo(), which violates encapsulation.Why does it violate encapsulation? BBB is a subclass of AAA, not just any class.So I design class AAA.
    AAA's constructor requires that AAA's foo() be invoked to initialize.
    AAA cannot control the behavior of BBB.
    BBB subclasses AAA, and overrides foo().
    If BBB's foo() does not invoke super(), AAA cannot initialize and thus neither can BBB.
    I see more what you're talking about. Well first of all you don't have foo() invoking super() you have B() doing it - small point but worth getting straight. I never said, and didn't mean that your code was desireable BTW ... I said it's understandable and a good learning devise. Two other posters gave you good advice as to what to do about it. I'll give you another. make foo() private instead of public. There is no reason to show all your implementation code to everyone and good reasons not to. If foo() should not be called by anything but the ctor or AAA, then hide it. There is not reason that I can see to override that method either. AAA should be initialized only by AAA, and BBB by BBB. So you call foo instead aaaInitialize() and foo in BBB bbbinitialize.
    Further, in the AAA constructor, a private variable is accessed "x", and then in the next line a method of a subclass is invoked. This blurs the boundary between what is hidden by the super class and exposed by a subclass (breaking encapsulation).
    I would just like to ask:
    Invoking public/protected instance methods in the constructors of non-final classes is absolutely forbidden, right?No it's not forbidden at all.The super class looses the ability to initialize itself. It becomes dependent on subclass behavior which breaks encapsulation.
    I am not asking why that happens. Rather, I just want to confirm the answer is "yes", it is forbidden. Or, if there are cases when it is ok, I am interested in learning them.You should do a Topeka on the subject.ok.
    Doing more that initializing instance variables in a constructor seems intriguing.
    It's done all the time. For example, in the constructor you might all methods like: "createAndBuildGUI()", which would build the graphics part of a desktop app - instead of doing all that code directly in the one constr method. Just one example. IDE's like Eclipse do things like this.
    But doing so could create weird situations (as in AAA's constructor) where you can access the private variable "x" of AAA and then invoke the BBB's foo().This is not wierd - it's designed to work like this.I just don't get it. A super class should never be allowed to invoke subclass's methods. The super class has no idea what the subclass's methods would do, so how could this be a reliable way to code? A class that invokes protected/public methods in the constructor is fragile and breakable. A concrete class should always be able to initialize itself regardless of what subclasses do.
    As jschell hinted, I totally lost focus on what a "constructor" is suppose to do: just initialize the object and get it ready to roll, and nothing more. no behavior. thanks.

  • Extending a class, its constructor inherited ?

    class a extends JFrame
    xxxxxxxx
    public void a()
    xxxxxxxxxx
    class someclass
    a myA = new a();
    ================
    there is a constructor -> JFrame(String title) in JFrame.
    when i create an instance of this class a this way which extends JFrame, do i overwrite the constructor JFrame(String title) ? what if i want to have a constructor that i can use to create the instance of a this way ->
    a myA = new a("my title")
    how should i do it? and as for a good java programmer, what is the best and most efficient way ?
    thank you

    hi,
    class a extends JFrame
    xxxxxxxx
    public void a()
    super();
    public void a(String title)
    super(title);
    class someclass
    a myA = new a("My Title");
    Phil

  • Another Inheritance Question, please help.

    Below is a setup of two packages and three classes:
    package com.foo.package1
    * This is the main superclass.
    public class SuperClass extends Object {
        public SuperClass () {
        protected getFoo() {
            return "foo";
    }here is the second package:
    package com.foo.package2
    import com.foo.package1.SuperClass;
    * This class extends SuperClass. Obviously, I removed
    * all methods for brevity.
    public class SubClass extends SuperClass {
        public SubClass () {
            super();
    * This class extends SubClass. A method here is supposed to
    * create an instance of the SuperClass and call a method on it.
    * In this case, {SuperClass#getFoo()} is called.
    public class SubSubClass extends SubClass {
        public SubSubClass () {
            super();
        public void method() {
            SubClass sc = new SubClass();
            System.out.println (
                    sc.getFoo());
    }Now why do I get a compile exception "getFoo() has protected access in com.foo.package1.SuperClass"? Should that be the case?
    Thanks in advance.
    Georg.

    It isn't a bug. Saying that protected members of a class are accessible from subclasses is not exactly true.
    From the JLS: 6.6.2 Details on protected Access
    A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
    SubSubClass is not responsible for the implementation of SuperClass. So basically, a class can only have access to protected members defined in a superclass if either:
    a) it is in the same package
    - or -
    b) the type of the reference used to access those members is that class, or one of it's subclasses.

  • Jframe inheritance question

    hi why is it when i set the variable inside secondframe class
    it just doesn't stick. i have a example that describes my problem better.
    i can see that when void show is called that it makes a new instance of
    second frame class so how would i fix this.
    i know i could scope int x through the show method and use it that way
    but im wanting to change varibles inside second class dynamicly
    any ideas thanks
    firstclass with frame1
    public class Main {
        public static void main(String[] args) {
              firstframe frame = new firstframe();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(270, 500);
              frame.setVisible(true);
            frame.setAlwaysOnTop(true);
    class firstframe extends JFrame
        private int x = 10;
        firstframe(){
        super.setTitle("first frame");
        System.out.println("first result :" + x);
        secondframe frame2 = new secondframe();
        secondclass.show();
    }second class
    public class secondclass {
        public static void show()
              secondframe frame = new secondframe();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(270, 500)thanks;
              frame.setVisible(true);
            frame.setAlwaysOnTop(true);
    class secondframe extends JFrame
        private int x;
        public secondframe(){
            super.setTitle("second frame");
            System.out.println("end result :" + x);
        public void setvaribles(int x){
            this.x = x;
    }

    Use proper Java naming conventions.
    Class names should be upper cased: ie FirstFrame, not firstframe.
    Method names are also upper cased except the first word: ie. setVariables, not setvariables.
    Why is show a static method? The only static method should be the main(...) method.
    You don't even need a show() method, the code to create the frame should be in the constructor.
    Also, applications should only have a single JFrame. Other windows should be JDialogs.

  • Inheritance Question part 2

    class ClassA
    public void sayHelloInA() { System.out.println("Hello in class A"); }
    public void show() { System.out.println("Show in ClassA"); }
    class ClassB extends ClassA
    public void sayHelloInB() { System.out.println("Hello in class B"); }
    public void show() { System.out.println("Show in ClassB"); }
    public class Test
    public static void main(String[] args)
    ClassA c = new ClassB();
    c.sayHelloInB();
    c.show();
    Why c.sayHelloInB() does not compile but c.show() compiles and runs (which displays "Show in ClassB")

    Russell53 wrote:
    Why c.sayHelloInB() does not compile but c.show() compiles and runs (which displays "Show in ClassB")The answer was already posted in your [previous thread|http://forums.sun.com/thread.jspa?threadID=5372352]. Please continue the discussion there.

  • Newbie inheritance question

    I have created a base class which implements cloneable (and I know the clone function works). I have also created two classes derived from the base class (which don't have cloneable implemented).
    Is it possible to "clone" the base class components of both derived classes. Here is what I mean
    //both derived from class1 which implements clone()
    class2 c2
    class3 c3
    c2 = c3.clone(); //I just want to clone the c1 member variables
    How do you go about doing this correctly.

    You won't be able to do c2 = c3.clone(), because c3.clone() will return a reference to an instance of class3, which is not a subclass of class2.
    The correct first step of the clone() method is to call super.clone(), which will give you an instance of the same class as the object you're cloning, with all the fields set to the same values. You can then change some fields' values before returning the result.

Maybe you are looking for

  • Suddenly can't enter anything in some blank search fields, dropdowns not working, and javascript popups freeze randomly. WTH?

    I noticed a few random things not working on my computer in the last month or so, and I tried everything I can think of to figure out what it is...still haven't figured it out yet. Some examples - I was on ebay, and the tracking number I clicked on f

  • If I ordered an iPhone with AT&T, will it take longer for it to ship?

    Okay, so last wednesday (July 7th), I ordered a 16 GB Black iPhone 4 from the AT&T store near my house (I live in Houston, TX)-the lady at the store said it would take 7-10 days to get it, but the Apple website said shipping takes 3 weeks...what am I

  • PreparedStatement reuse

    Is it possible to use a PreparedStatement after its resultset has been processed? It seems to me like once you iterate through the ResultSet the PreparedStatement can not be executed again with a different set of parameters. Is this correct? I'm usin

  • Issue when importing  web service  into CTI Aspect ECS server

    Hi Experts, We have an SOAP to ABAP Proxy interface in our production XI system. this interface connects CTI ASPECT ECS system to SAP CRM system (via XI or PI system). CTI ASpect system consumes the web service exposed by XI system. recently we edite

  • Content Mamgement Q

    When using a content management system how do they populate the page when it has multiple items? Lets say the body has one content and the sidebar has another. My inital thought was two queries, but that sounds like it could be a little busy as the n