java - Writing and accessin child class variable and function except those being inherited from parent class -
i trying implement , access new data members , new member function in concrete class other 1 inherited parent class. can not that.
real question follows:
create abstract class a 2 data members , 2 member functions. create 2 concrete classes of a class, named b , c. each concrete class should have 2 new data members , 2 new member functions. data members , member functions in 2 classes should not same. write main() methods create objects of each subclass, , send them enough messages show methods work.
please help.
the code --
import java.util.*; abstract class { abstract void display(); abstract void rules(); int players; int length; } class b extends { b(int a,int b) { players=a; length=b; } void rules() { system.out.println("b rules"); } void display() { system.out.println("in b players=" +players); } } class c extends { c(int a,int b) { players = a; length = b; } void summary()// problem here . can not access summary { system.out.println("rules"); } void display() { system.out.println("in c players=" +players + " length=" +length); } } public class batandball { public static void main(string args[]) { system.out.println("airtel champions league"); obj = new b(10,3); obj.display(); obj1 = new c(11,8); obj1.display(); obj1.summary(); // problem here . can not access summary } }
you cannot access because variable created of type a, not c. know obj1 c polymorphism makes not c. can see, declaring a here:
a obj1; no matter values put in obj1, still of type a. how call summary? need cast! change obj1's type c:
(c)obj1 and can use call summary:
((c)obj1).summary(); that's easy isn't it?
and way, c class doesn't implement rules defined in a. should implement or code won't compile.
Comments
Post a Comment