8 Inheritance in Java
8 Inheritance in Java
Single Inheritance
• When a class inherits from only one class, it is called single
inheritance.
• Interfaces provide the benefits of multiple inheritance without
drawbacks.
• Syntax of a Java class is as follows:
• Name
• Return type
• Argument list
Example
Public String () {
Important notes
1. Final class cannot be subclass.
2. Final method cannot be overridden.
3. Final variable such as a constant and any attempt
to change the value of a final variable causes a
compiler error.
package Inheritance;
public class Cars extends Transportation{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
meth1();// don't need an object ref. here >>>> Why????
System.out.println("The variable x from Super Class is
"+x);
meth2(); // This method is error because has private
modifier
System.out.println(" The variable Y from Super
Class"+y);
}
}
class B extends A{
public class C {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
B Sub_Class=new B();
Sub_Class.test();
}
}
class B extends A{
package Inhertiance;
public class C {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
B Sub_Class=new B();
Sub_Class.test();
}
}
public class A {
protected int a=9;
void test_method()
{
System.out.println("The Super Class Method");
}
}
class B extends A{
void test1 (){
super.test_method();
test2();
}
void test2(){
System.out.println("The method in SupClass");
}
}
package Inhertiance;
public class C {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
B m=new B();
m.test1();
}
}
void attributes() {
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}