Thread: Inheritance

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    Kiev, Ukrain
    Posts
    89
    Rep Power
    2

    Inheritance


    Hi, i'm trying to understand the Inheritance machine in 100%. Can u help mi with that ?

    I have an error in my code."No enclosing instance of type Inheritance is accessible. Must qualify the allocation with an enclosing instance of type
    Inheritance (e.g. x.new A() where x is an instance of Inheritance)."

    I done the same with more complex classes and everything was ok, but here is something wrong.
    Code:
    class Inheritance {
    	
    	public static void main(String[] args){
    		new B().sum(); // here it is (error)
    	}
    	
    	public class A{
    		int i=1, j=0;
    		
    		void showij(){
    			System.out.println("i= " + i);
    			System.out.println("j= " + j);
    			
    		}
    	}
    	
    	public class B extends A{
    		int k;
    		
    		void showk(){
    			System.out.println("k= " + k);
    		}
    		
    		public void sum(){
    			System.out.println("i+j+k= " + (i+j+k));
    		}
    	}
    }
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,022
    Rep Power
    1285
    B is an inner class of Inheritance and cannot be instantiated from a static context. In the main method, you'll need to create an instance of Inheritance and use that instance to create a new instance of B.

    Code:
    new Inheritance().new B()
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    Kiev, Ukrain
    Posts
    89
    Rep Power
    2
    Thank you! now it works .

IMN logo majestic logo threadwatch logo seochat tools logo