我用谷歌搜索了几次,但仍然无法理解超类型方法。谁能解释一下这是什么?
问问题
23350 次
6 回答
32
OOPS 中有超类型和子类型的概念,在 java 中这种关系是通过继承实现的,即使用extends
关键字:
class A {} // super class
class B extends A {} //sub class
在超类中声明的任何成员(字段、方法)都称为超类型。
因此,在上述上下文中,如果类A
具有类似的方法
class A {
void set()
}
Set 是 class 的超类型方法B
。
但是,请注意,如果有另一个类说C
:
class C {
void set()
}
然后set()
方法不是类的超类型,C
因为类A
和类之间没有关系C
(关系是通过extends
关键字创建的,用于继承)。
于 2013-02-28T08:14:42.557 回答
3
如果您正在谈论调用超级方法,则应尝试以下操作
- 使用方法公共方法创建一个类,例如
printSomething()
public void printSomething() { System.out.println("hello, I am the first class"); }
- 创建从第一个类继承的第二个类并覆盖 printSomething 方法
@override public void printSomething() { super.printSomething(); }
- 编写一个小程序,调用
printSomething
类二的方法,看看会发生什么
于 2013-02-28T08:36:32.533 回答
2
超级在建造者级别
class SuperClass
{
int num=10;
public void display()
{
System.out.println("Superclass display method");
}
}
class SubClass extends SuperClass
{
int num=20;
public void display()
{
System.out.println("the value of subclass variable name:"+num);
System.out.println("Subclass display method");
}
public void Mymethod()
{
super.display();
System.out.println("the value of superclass variable name:"+super.num);
}
public static void main(String[] args)
{
SubClass obj=new SubClass();
obj.Mymethod();
obj.display();
}
}
于 2017-04-07T09:57:37.507 回答
1
在java中,每件事都是对象,方法也是类java.lang.reflect.Method的对象,所以方法的超类型可以被认为java.lang.reflect.Method
是AccessibleObject
.
于 2013-02-28T08:19:05.813 回答
1
超类型和子类型是继承的属性,即为了代码的可重用性。我给你举了超级类和子类的例子。更多你可以关注这里。
使用系统;
namespace MultilevelInheritance
{
public class Customer
{
public float fDis { get; set; }
public Customer()
{
Console.WriteLine("I am a normal customer.");
}
public virtual void discount()
{
fDis = 0.3F;
Console.WriteLine("Discount is :{0}", fDis);
}
}
public class SilverCustomer : Customer
{
public SilverCustomer()
: base()
{
Console.WriteLine("I am silver customer.");
}
public override void discount()
{
fDis = 0.4F;
Console.WriteLine("Discount is :{0}", fDis);
}
}
class GoldenCustomer : SilverCustomer
{
public GoldenCustomer()
{
Console.WriteLine("I am Golden customer.");
}
public override void discount()
{
fDis = 0.6F;
Console.WriteLine("Discount is :{0}", fDis);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultilevelInheritance
{
class Program
{
static void Main(string[] args)
{
Customer objCus = new Customer();
objCus.discount();
SilverCustomer objSil = new SilverCustomer();
objSil.discount();
GoldenCustomer objGold = new GoldenCustomer();
objGold.discount();
Console.ReadLine();
}
}
}
于 2016-09-11T15:02:34.287 回答
1
Super 用于调用在 3 个级别变量构造函数和方法级别使用的父类属性
1.超级变量
class Super
{
int age;
Super(int age)
{
this.age=age;
}
public void getAge()
{
System.out.println(age);
}
}
class Sub extends Super
{
Sub(int age)
{
super(age);
}
public static void main(String[] args)
{
Super obj=new Super(24);
obj.getAge();
}
}
于 2017-04-07T09:53:42.643 回答