Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance question (Java OCA 8 Programmer I Study Guide, Sybex)

 
Aleksandra Pestova
Ranch Hand
Posts: 36
2
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a following example in the study guide:

Because Java allows only one public class per fi le, we can create two fi les, Animal.java
and Lion.java, in which the Lion class extends the Animal class. Assuming they are in the
same package, an import statement is not required in Lion.java to access the Animal class.
Here are the contents of Animal.java:

And here are the contents of Lion.java:


Why can Lion use method getAge() directly?
Is it because Lion inherited all the methods from Animal, so getAge() now belongs to the "Lion" as well?
 
Ganesh Patekar
Bartender
Posts: 696
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aleksandra Pestova wrote:Is it because Lion inherited all the methods from Animal, so getAge() now belongs to the "Lion" as well?
  • If you read carefully next 5 lines of explanation with one example then we can understand it, methods of super class i.e. methods of Animal,  having public or protected or package -private(If subclass and super class present in same package) access modifier are accessible in subclass i.e. Here Lion.
  • In given example getAge() method of Animal is having public access modifer so accessible in subclass Lion.
  • If you notice next example where they are trying to access age an instance variable of Animal in subclass Lion, which is having private access modifier means private int age is accessible within Animal class only so that code will not compile.
  •  
    Aleksandra Pestova
    Ranch Hand
    Posts: 36
    2
    Firefox Browser Java Notepad
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you! Should read more carefully next time.
     
    Ganesh Patekar
    Bartender
    Posts: 696
    23
    Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    happens  , You're welcome
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic