Monday, 11 May 2015

Inheritance Example

Exported from Notepad++
import java.util.Scanner; class Player { protected String name; protected String cate; //if private access specifier then subclass objects cannot access them,So protected. Player(String name_cate) { cate=name_cate; System.out.println(" "+cate); System.out.println("Enter player name "); Scanner sc=new Scanner(System.in); name=sc.nextLine(); } public void display(){ System.out.println(" "+cate); System.out.println("The player name is : "+name); } } //all three classes extending one class hierarchical inheritance class Cricket extends Player{ Cricket(){ //super is used to invoke super class methods and variables super("Cricket"); } public void display(){ super.display(); //invoking super class display method. } } class Football extends Player{ Football() { super("Football"); //if only super keyword is used then constructor of super class is invoked. } public void display(){ super.display(); } } class Hockey extends Player{ Hockey(){ super("Hockey"); } public void display(){ super.display(); } } public class Inherit { public static void main(String[] args) { Cricket objc=new Cricket(); Football objf=new Football(); Hockey objh=new Hockey(); //creating objects for each subclass objc.display(); objf.display(); objh.display(); } }


No comments:

Post a Comment