Results 1 to 2 of 2
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Very interesting Abstract Class behavior. Please Help :)

    Java Code:
    public abstract class MyAbstractClass {
    	int age = 15;
    	public void printAge() {
    		System.out.println(age);
    	}
    }
    
    public class ConcClassA extends MyAbstractClass {
    	int age = 0;
    	ConcClassA(){
    		age = 45;
    	}
    	@Override
    	public void printAge() {
    		System.out.println(age);
    	}
    }
    
    public class TestLearningPackage {
    	public static void main(String[] args) {
    		MyAbstractClass testA = new ConcClassA();
    		System.out.println("testA.age : " + testA.age);
    		System.out.print("testA.printAge(): ");
    		testA.printAge();
    	}
    }
    When I run this code, the output is:

    testA.age : 15
    testA.printAge(): 45


    The question is:
    When I comment out: int age = 0 the output is now: ( on line 9 )


    testA.age : 45
    testA.printAge(): 45


    How does commenting int age = 0 changes the testA.age from 15 to 45 ?

  2. #2
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default Re: Very interesting Abstract Class behavior. Please Help :)

    The field 'age' in ConcClassA hides the field 'age' in its super class. If you remove this field from the sub-class, then the variable 'age' will have to refer to the field in the super class. This is nothing out of order, its normal behaviour.

    Please read over:
    Inheritance (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)

Similar Threads

  1. abstract method-abstract class
    By durgaprasad1407 in forum New To Java
    Replies: 1
    Last Post: 04-29-2011, 06:58 PM
  2. Replies: 4
    Last Post: 04-14-2011, 11:42 AM
  3. Replies: 6
    Last Post: 02-11-2009, 10:51 AM
  4. Object class's equals() method behavior????
    By skyineyes in forum New To Java
    Replies: 4
    Last Post: 07-19-2008, 11:58 PM
  5. Replies: 0
    Last Post: 04-02-2008, 07:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •